问题描述
以下脚本创建了一个 Figure
实例,该实例在辅助网格线后面具有蓝色直方图,而蓝色网格直方图在橙色累积直方图之后.
将matplotlib.pyplot导入为plt将numpy导入为npplt.style.use("seaborn-darkgrid")np.random.seed(42)foo = np.random.randn(1000)无花果,ax = plt.subplots()ax.hist(foo,bins = 50)ax2 = ax.twinx()ax2.hist(foo, bins=50, 密度=真, 累积=真, histtype="step", color="tab:orange")plt.show()
我正在寻找一种将网格线置于蓝色直方图后面的方法,并在
The following script creates a Figure
instance with a blue histogram behind secondary grid lines, which themselves are behind an orange cumulative histogram.
import matplotlib.pyplot as plt
import numpy as np
plt.style.use("seaborn-darkgrid")
np.random.seed(42)
foo = np.random.randn(1000)
fig, ax = plt.subplots()
ax.hist(foo, bins=50)
ax2 = ax.twinx()
ax2.hist(
foo, bins=50, density=True, cumulative=True, histtype="step", color="tab:orange"
)
plt.show()
I was looking for a way to put the grid lines behind the blue histogram, and found a related issue at matplotlib/matplotlib#7984. It says
and this explains why ax2.set_axisbelow(True)
has no effect on the primary Axes
.
Can I achieve my goal in some way? Workarounds are welcome (I suppose there isn't a canonical solution according to the quote above).
Your desired drawing order is (first is most to the back)
- grid for axes
- grid for twin axes
- plot in axes
- plot in twin axes
However this is not possible as seen by the comment
What this means is that you need 4 axes instead of two.
- axes for grid of primary y scale
- axes for grid of secondary y scale
- axes for plot on primary y scale
- axes for plot on secondary y scale
This could look like this:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
foo = np.random.randn(1000)
fig, ax1a = plt.subplots() # ax1a for the histogram grid
ax2a = ax1a.twinx() # ax2a for the cumulative step grid
ax1b = ax1a.twinx() # ax1b for the histogram plot
ax2b = ax1a.twinx() # ax2a for the cumulative step plot
# Link the respective y-axes for grid and plot
ax1a.get_shared_y_axes().join(ax1a, ax1b)
ax2a.get_shared_y_axes().join(ax2a, ax2b)
# Remove ticks and labels and set which side to label
ticksoff = dict(labelleft=False, labelright=False, left=False, right=False)
ax1a.tick_params(axis="y", **ticksoff)
ax2a.tick_params(axis="y", **ticksoff)
ax1b.tick_params(axis="y", labelleft=True, labelright=False, left=True, right=False)
ax2b.tick_params(axis="y", labelleft=False, labelright=True, left=False, right=True)
# Spines off
for ax in [ax1a, ax2a, ax1b]:
for k,v in ax.spines.items():
v.set_visible(False)
ax1b.hist(foo, bins=50)
ax2b.hist(
foo, bins=50, density=True, cumulative=True, histtype="step", color="tab:orange"
)
ax1a.grid()
ax2a.grid()
plt.show()
这篇关于如何将次要轴上的网格线放在主要图的后面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!