当使用Axes.twinx()创建具有两个不同高度刻度的重叠条形图时,我无法将'twin‘轴集的垂直网格线设置为可见。但是水平线工作得很好。对如何解决这个问题有什么想法吗?
下面是一些示例代码,说明了我想做什么和不能做什么。如图所示,垂直网格线被ax2的红色条所隐藏,而我希望网格线在所有条中都可见。
# Create figure and figure layout
ax1 = plt.subplot()
ax2 = ax1.twinx()
# Example data
x = [0, 1, 2, 3, 4, 5]
h1 = [55, 63, 70, 84, 73, 93]
h2 = [4, 5, 4, 7, 4, 3]
# Plot bars
h1_bars = ax1.bar(x, h1, width=0.6, color='darkblue')
h2_bars = ax2.bar(x, h2, width=0.6, color='darkred')
# Set y limits and grid visibility
for ax, ylim in zip([ax1, ax2], [100, 10]):
ax.set_ylim(0, ylim)
ax.grid(True)

出现此错误是因为ax2的垂直网格线设置为不可见。这可以通过设置ax1.grid(False)进行测试,在这种情况下,只有水平网格线。

我尝试了ax1.xaxis.grid(True),ax1.yaxis.grid(True),ax2.xaxis.grid(True)和ax2.yaxis.grid(True)的所有组合,但没有任何运气。在这件事上的任何帮助都深表感谢!
发布于 2019-03-27 22:59:22
您可以恢复ax1和ax2的角色,这样蓝色条显示在ax2上,红色条显示在ax1上。然后,您需要将两个轴放在背景中,并在绘图的另一侧勾选相应的y轴。
import matplotlib.pyplot as plt
# Create figure and figure layout
ax1 = plt.subplot()
ax2 = ax1.twinx()
# Example data
x = [0, 1, 2, 3, 4, 5]
h1 = [55, 63, 70, 84, 73, 93]
h2 = [4, 5, 4, 7, 4, 3]
# Plot bars
h1_bars = ax2.bar(x, h1, width=0.6, color='darkblue')
h2_bars = ax1.bar(x, h2, width=0.6, color='darkred')
# Set y limits and grid visibility
for ax, ylim in zip([ax1, ax2], [10, 100]):
ax.set_ylim(0, ylim)
ax.grid(True)
ax1.set_zorder(1)
ax1.patch.set_alpha(0)
ax2.set_zorder(0)
ax1.yaxis.tick_right()
ax2.yaxis.tick_left()
plt.show()

https://stackoverflow.com/questions/55373097
复制相似问题