我有一组 3 元组,每个 3 元组由 (var1, var2, result) 组成。9 个三元组列表示例:
<type 'list'>:
[(4, 0.7, 0.8530612244898, 0.016579670213527985),
(4, 0.6, 0.8730158730157779, 0.011562402525241757),
(6, 0.8, 0.8378684807257778, 0.018175985875060037),
(4, 0.8, 0.8605442176870833, 0.015586992159716321),
(2, 0.8, 0.8537414965986667, 0.0034013605443334316),
(2, 0.7, 0.843537414966, 0.006802721088333352),
(6, 0.6, 0.8480725623582223, 0.01696896774039503),
(2, 0.6, 0.84693877551025, 0.010204081632749995),
(6, 0.7, 0.8577097505669444, 0.019873637350220318)]
现在我想创建一个热图。Var1
可以是值[2,4,6]
并且Var2
可以是[0.6, 0.7, 0.8]
。共有 9 个结果。
这是我用来绘制热图的代码:
# list of 3-tuples to 3 lists: x, y and weights
# x (var1) = [2,4,6]
# y (var2) = [0.6, 0.7, 0.8]
# weights (res) = [....] (9 values)
x, y = np.meshgrid(x, y)
intensity = np.array(weights)
plt.pcolormesh(x, y, intensity)
plt.colorbar() # need a colorbar to show the intensity scale
plt.show()
我觉得奇怪的是只有 4 个部分,但我预计会有 9 个(3x3)。有人可以阐明我在这里做错了什么吗?
您首先需要对数组进行排序,以便以后能够从中获取正确的矩阵。这可以使用numpy.lexsort
.
可以在这个问题中找到少一行和一列的原因:有人可以解释这个 matplotlib pcolormesh quirk 吗?
因此,您需要决定前两列中的值是表示图中矩形的边缘还是它们是中心。在任何情况下,您都需要比彩色矩形多一个值才能将矩阵绘制为pcolormesh
。
data = [ (4, 0.7, 0.8530612244898, 0.016579670213527985),
(4, 0.6, 0.8730158730157779, 0.011562402525241757),
(6, 0.8, 0.8378684807257778, 0.018175985875060037),
(4, 0.8, 0.8605442176870833, 0.015586992159716321),
(2, 0.8, 0.8537414965986667, 0.0034013605443334316),
(2, 0.7, 0.843537414966, 0.006802721088333352),
(6, 0.6, 0.8480725623582223, 0.01696896774039503),
(2, 0.6, 0.84693877551025, 0.010204081632749995),
(6, 0.7, 0.8577097505669444, 0.019873637350220318)]
import numpy as np
import matplotlib.pyplot as plt
# sort the array
data=np.array(data)
ind = np.lexsort((data[:,0],data[:,1]))
data = data[ind]
#create meshgrid for x and y
xu = np.unique(data[:,0])
yu = np.unique(data[:,1])
# if values are centers of rectangles:
x = np.append(xu , [xu[-1]+np.diff(xu)[-1]])-np.diff(xu)[-1]/2.
y = np.append(yu , [yu[-1]+np.diff(yu)[-1]])-np.diff(yu)[-1]/2.
# if values are edges of rectanges:
# x = np.append(xu , [xu[-1]+np.diff(xu)[-1]])
# y = np.append(yu , [yu[-1]+np.diff(yu)[-1]])
X,Y = np.meshgrid(x,y)
#reshape third column to match
Z = data[:,2].reshape(3,3)
plt.pcolormesh(X,Y,Z, cmap="jet")
plt.colorbar()
plt.show()
可以使用 选择相同的图imshow
,您不需要网格,而是指定extent
图的 。
import numpy as np
import matplotlib.pyplot as plt
# sort the array
data=np.array(data)
ind = np.lexsort((data[:,0],data[:,1]))
data = data[ind]
#create meshgrid for x and y
xu = np.unique(data[:,0])
yu = np.unique(data[:,1])
x = np.append(xu , [xu[-1]+np.diff(xu)[-1]])-np.diff(xu)[-1]/2.
y = np.append(yu , [yu[-1]+np.diff(yu)[-1]])-np.diff(yu)[-1]/2.
#reshape third column to match
Z = data[:,2].reshape(3,3)
plt.imshow(Z, extent=[x[0],x[-1],y[0],y[-1]], cmap="jet",
aspect="auto", origin="lower")
plt.colorbar()
plt.show()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句