Matplotlib:imshow与第二个y轴

2024-09-28 23:48:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用imshow()在matplotlib中绘制二维数组,并在第二个y轴上用散点图覆盖它

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))

如果我只运行到最后一行的所有内容,那么我的阵列将完全可视化:

That's what it is supposed to look like!

但是,如果我添加第二个y轴(ax2=ax1.twinx())作为散点图的准备,它将更改为不完整的渲染:

Incomplete visualisation of array

有什么问题吗?我在上面的代码中留下了几行描述添加散点图的内容,尽管这似乎不是问题的一部分


Tags: thenppltshapesetimshowarangeax1
1条回答
网友
1楼 · 发布于 2024-09-28 23:48:47

在托马斯·库恩(Thomas Kuehn)指出的GitHub讨论之后,这个问题在几天前就解决了。如果没有现成的构建,这里有一个使用aspect='auto'属性的修复程序。为了得到很好的规则框,我使用数组尺寸调整了图形x/y。轴自动缩放功能已用于删除一些额外的白色边框

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)

结果:

enter image description here

相关问题 更多 >