双网格线的可见性

问题描述 投票:2回答:1

使用Axes.twinx()创建具有两个不同高度比例的重叠条形图时,我无法设置“双轴”设置的垂直网格线。水平线工作正常。有关如何解决此问题的任何想法?

下面是一些示例代码,说明了我想要做什么以及我不能做什么。如图所示,垂直网格线被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)的所有组合而没有任何运气。对此事的任何帮助深表感谢!

python matplotlib
1个回答
2
投票

您可以恢复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()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.