python - 如何将网格线从辅助轴放在主图后面?
问题描述
以下脚本创建了一个Figure
实例,在辅助网格线后面有一个蓝色直方图,而辅助网格线本身位于橙色累积直方图后面。
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()
我正在寻找一种将网格线放在蓝色直方图后面的方法,并在matplotlib/matplotlib#7984发现了一个相关问题。它说
您不能将来自一个轴的艺术家的绘图顺序与来自另一个轴的艺术家的绘图顺序交错
这解释了为什么ax2.set_axisbelow(True)
对 primary 没有影响Axes
。
我能以某种方式实现我的目标吗?欢迎使用变通方法(我想根据上面的引用没有规范的解决方案)。
解决方案
您想要的绘图顺序是(首先是最靠后的)
- 轴的网格
- 双轴网格
- 在轴上绘图
- 双轴绘图
但是,正如评论所见,这是不可能的
您不能将来自一个轴的艺术家的绘图顺序与来自另一个轴的艺术家的绘图顺序交错
这意味着您需要 4 个轴而不是两个。
- 主要 y 比例网格的轴
- 次级 y 刻度网格的轴
- 主要 y 刻度上的绘图轴
- 次要 y 尺度上的绘图轴
这可能看起来像这样:
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()
推荐阅读
- javascript - Facebook 跟踪按钮事件上的像素
- redux - 运行应用程序时遇到错误
- node.js - 文件中的多个架构不起作用
- wordpress - 页面 VS 子域 - 不知道该走哪条路
- python - 在 Flask-Restplus Swagger UI 中停用表单输入
- c++ - 虚函数替换为非虚函数
- ruby - Ruby gsub 然后冻结获取不同的 object_id
- elasticsearch - 从elasticsearch中的关键类别获取数据
- bash - Ansible 在任务中创建可重用的动态环境变量
- authentication - ASP.NET Core - 推荐的自定义身份验证方法