Matplotlib twinx-aligning with yticklabels and yticks

时间:2017-08-01 19:04:52

标签: python matplotlib

还有其他一些问题,但似乎没有一个问题涵盖我的确切问题/他们的解决方案都没有“纠正”我的问题。

import matplotlib.pyplot as plt
calendar = [[1,0,0,1,1,0,1],[0,0,1,1,1,0,1]]
fig, ax = plt.subplots()
namelist = ['alpha','beta']
yticks = [n for n in range(len(namelist))]
ax.set_yticks(yticks)
ax.set_yticklabels(namelist)
ax2 = ax.twinx()
ax2.set_yticks(ax.get_yticks())
ax2.set_yticklabels(['gamma','delta'])    

im = ax.imshow(calendar, interpolation='none', cmap='summer')
plt.show()

enter image description here

当然鞋面只是一个非常简化的版本,但它应该足以看到问题:当评论两个“ax2线”时,情节是我想要的,但是当添加第二个y轴时,情节会像我不想要它。我希望alpha / beta与gamma / delta处于同一高度(这样就不会留下空白区域)但是我现在已经失败了很长时间。我已经尝试了get_yticks()函数(如某些类似问题所提出的那样),但它没有帮助。 提前谢谢!

编辑:一个小细节:解决方案在某种意义上应该是“可扩展的”,它应该处理更多的y值(alpha,beta,delta,......)和它们的前两个对应物。

编辑2 :(我不确定发布新问题是否有用,所以我只是问这里:)我现在正在尝试添加一个网格。我再次尝试了很多,但似乎没有任何帮助,充其量我可以得到一个y轴网格。检查以下代码(并对那些未注释的行尝试相同的操作!):<​​/ p>

import matplotlib.pyplot as plt
calendar = [[1,0,0,1,1,0,1],[0,0,1,1,1,0,1]]
fig, ax = plt.subplots()
namelist = ['alpha','beta']
yticks = [n for n in range(len(namelist))]
ax.set_xticks([num for num in range(len(calendar[0]))])
ax.set_xticks([num-0.5 for num in range(len(calendar[0]))],minor=True)
ax.set_yticks(yticks)
ax.set_yticks([num-0.5 for num in range(len(namelist))],minor=True)
ax.set_yticklabels(namelist)
im = ax.imshow(calendar, interpolation='none', cmap='summer')
ax.set_adjustable('box-forced')
ax.xaxis.grid(which='major',alpha=1,color='k',lw=2)
ax.xaxis.grid(which='minor',alpha=1,color='k',lw=2)
ax.yaxis.grid(which='minor',alpha=1,color='k',lw=2)

#ax2 = ax.twinx()
#ax2.set_yticks(ax.get_yticks())
#ax2.set_yticklabels(['gamma','delta'])    
#im2 = ax2.imshow(calendar, interpolation='none', cmap='summer')
#ax2.set_adjustable('box-forced')

plt.show()

如何让网格显示?这是一张如何拍摄的照片(没有ax2)。基本上不应该代码完全给我相同但右边的第二个标签?! enter image description here

1 个答案:

答案 0 :(得分:2)

获得所需内容的一种方法是在ax2上重新绘图:

im2 = ax2.imshow(calendar, interpolation='none', cmap='summer')

它并不完美,但它确实有效。

ticks in correct positions

修改

根据答案here,如果您在轴上进一步使用set_adjustable,则空格会消失:

import matplotlib.pyplot as plt
calendar = [[1,0,0,1,1,0,1],[0,0,1,1,1,0,1]]
fig, ax = plt.subplots()
namelist = ['alpha','beta']
yticks = [n for n in range(len(namelist))]
ax.set_yticks(yticks)
ax.set_yticklabels(namelist)
im = ax.imshow(calendar, interpolation='none', cmap='summer')
ax.set_adjustable('box-forced')

ax2 = ax.twinx()
ax2.set_yticks(ax.get_yticks())
ax2.set_yticklabels(['gamma','delta'])    
im2 = ax2.imshow(calendar, interpolation='none', cmap='summer')
ax2.set_adjustable('box-forced')

plt.show()

whitespace removed