我想绘制一个热图,以便更好地可视化散点图中的分布模式,但生成热图时遇到了一些问题。y轴上的数据从0扩展到15,x轴从0扩展到7
我参考了下面关于如何生成热图的帖子,并对下面的代码进行了编码,这似乎给了我一个散点图,似乎与我希望的散点图有很大的出入
Generate a heatmap in MatPlotLib using a scatter data set
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm as CM
x = [0.3178, 2.0857, 2.5922, 0.088, 0.3, 0.4006, 1.0241, 0.1913, 0.56, 1.1828, 2.6879, 5.8044, 0.3593, 1.8732, 10.8003, 0.3457, 1.7003, 0.1677, 0.7442, 1.5731, 0.4927, 0.4143, 0.558, 0.2486, 0.3009, 0.163, 2.645, 4.1364, 13.8043, 3.9997, 0.258, 0.78, 10.3991, 0.2425, 0.3335, 4.8002, 0.3529, 5.9263, 0.151, 0.34, 0.1146, 13.6505, 2.8802, 3.2738, 0.5562, 0.5067, 1.5142, 2.0373, 2.5427, 12.1005]
y = [4.4903, 6.8879, 5.6211, 5.1128, 1.8125, 4.9716, 2.6847, 5.3744, 6.5254, 3.875, 3.6667, 2.0, 6.9811, 6.0501, 6.0, 6.8478, 5.0, 5.3676, 3.403, 6.1015, 6.8793, 4.7684, 3.5934, 2.6224, 5.9319, 1.8191, 3.0554, 3.5207, 3.6786, 3.0, 5.9041, 1.9128, 6.3333, 5.4949, 5.7135, 6.0, 5.5348, 3.0, 5.2644, 5.8111, 1.093, 4.0, 7.0, 6.0, 3.8684, 4.8, 1.5283, 6.6932, 7.0, 4.0]
# plot the scatter_plot
xposition = [0,7]
plt.figure()
plt.plot(y,x,'r^', label='series_1',markersize=12)
plt.gcf().set_size_inches(11.7, 8.27)
ax = plt.gca()
ax.tick_params(axis = 'both', which = 'major', labelsize = 16)
for xc in range(0,xposition[-1]+1):
ax.axvline(x=xc, color='darkgrey', linestyle='--', linewidth = 2)
plt.xlabel('x', fontsize=18)
plt.ylabel('y', fontsize=18)
plt.xlim(xposition)
plt.ylim([0,15])
plt.legend(loc='upper right',fontsize = 'x-large')
# plot the heatmap
plt.figure()
heatmap, xedges, yedges = np.histogram2d(y, x, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
plt.clf()
plt.imshow(heatmap.T, extent=extent, interpolation='nearest', origin='lower')
plt.pcolormesh(xedges, yedges, heatmap, cmap=CM.RdBu_r, vmin=-7, vmax=7)
plt.gcf().set_size_inches(11.7, 8.27)
plt.show()
对于结果,首先,热图的绘图大小似乎不同于散点图,尽管我指定它们是相同的。其次,热图似乎与右下角聚集的散点图中的模式不匹配。请告诉我应该在哪里修改以得到正确的热图。谢谢你
下面的代码似乎可以解决这个问题。你犯了3个错误
你做了同样大小的图形,而不是轴。 我为散点图添加了一个设置的纵横比,以使纵横比相等,与热图中的相同
你画了一个imshow,然后在上面画了一个pcolormesh(你不需要两者都画)
pcolormesh出于某种原因期望热图相对于imshow所需要的进行转换。我把它转过来了
另外,为什么不尝试使用subplot,而不是下面示例中的两个数字呢?不过,添加色条可能会遇到一些问题,但这是可以解决的
相关问题 更多 >
编程相关推荐