Matplotlib:带有第二个 y 轴的 imshow [英] Matplotlib: imshow with second y axis
问题描述
我正在尝试使用imshow()在matplotlib中绘制二维数组,并在第二个y轴上用散点图覆盖它.
I'm trying to plot a two-dimensional array in matplotlib using imshow(), and overlay it with a scatterplot on a second y axis.
oneDim = np.array([0.5,1,2.5,3.7])
twoDim = np.random.rand(8,4)
plt.figure()
ax1 = plt.gca()
ax1.imshow(twoDim, cmap='Purples', interpolation='nearest')
ax1.set_xticks(np.arange(0,twoDim.shape[1],1))
ax1.set_yticks(np.arange(0,twoDim.shape[0],1))
ax1.set_yticklabels(np.arange(0,twoDim.shape[0],1))
ax1.grid()
#This is the line that causes problems
ax2 = ax1.twinx()
#That's not really part of the problem (it seems)
oneDimX = oneDim.shape[0]
oneDimY = 4
ax2.plot(np.arange(0,oneDimX,1),oneDim)
ax2.set_yticks(np.arange(0,oneDimY+1,1))
ax2.set_yticklabels(np.arange(0,oneDimY+1,1))
如果我只将所有内容运行到最后一行,我的数组就会完全可视化:
If I only run everything up to the last line, I get my array fully visualised:
但是,如果我添加第二个y轴(ax2 = ax1.twinx())作为散点图的准备工作,它将更改为这种不完整的渲染:
However, if I add a second y axis (ax2=ax1.twinx()) as preparation for the scatterplot, it changes to this incomplete rendering:
有什么问题吗?我在上面的代码中留下了几行描述散点图的添加,尽管它似乎不是问题的一部分.
What's the problem? I've left a few lines in the code above describing the addition of the scatterplot, although it doesn't seem to be part of the issue.
推荐答案
根据 Thomas Kuehn 指出的 GitHub 讨论,该问题已在几天前得到解决.如果没有易于使用的内置文件,请使用 aspect ='auto'属性进行修复.为了获得漂亮的常规框,我使用数组尺寸调整了图形x/y.轴自动缩放功能已被用于移除一些额外的白色边框.
Following the GitHub discussion which Thomas Kuehn has pointed at, the issue has been fixed few days ago. In the absence of a readily available built, here's a fix using the aspect='auto' property. In order to get nice regular boxes, I adjusted the figure x/y using the array dimensions. The axis autoscale feature has been used to remove some additional white border.
oneDim = np.array([0.5,1,2.5,3.7])
twoDim = np.random.rand(8,4)
plt.figure(figsize=(twoDim.shape[1]/2,twoDim.shape[0]/2))
ax1 = plt.gca()
ax1.imshow(twoDim, cmap='Purples', interpolation='nearest', aspect='auto')
ax1.set_xticks(np.arange(0,twoDim.shape[1],1))
ax1.set_yticks(np.arange(0,twoDim.shape[0],1))
ax1.set_yticklabels(np.arange(0,twoDim.shape[0],1))
ax1.grid()
ax2 = ax1.twinx()
#Required to remove some white border
ax1.autoscale(False)
ax2.autoscale(False)
结果:
这篇关于Matplotlib:带有第二个 y 轴的 imshow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!