【问题标题】:Matplotlib: Grid lines behind bars on twinned axes?Matplotlib:双轴上的网格线?
【发布时间】:2020-06-27 15:39:02
【问题描述】:

我正在使用 twiny() 在一个图表上绘制两个系列,并希望在条形后面有网格线。但是,默认情况下,行为是混合的:在原始坐标轴的元素前面和双胞胎的后面。

axis.set_axisbelow(True) 和 zorder=0 与 grid 调用都无法解决此问题。这是 matplotlib 中的错误吗?有人知道解决方法吗?

这里有一个例子来说明:

import matplotlib, matplotlib.pyplot as plt
print('matplotlib: {}'.format(matplotlib.__version__))

series1 = [1.25,2.25,3]
series2 = [12,9.75,6.75]
categories = ['A','B','C']

fig, axes1 = plt.subplots(nrows=1,ncols=1)
axes2 = axes1.twiny()

axes1.barh(categories, series1, color='red', align='edge', height=-0.4)
axes2.barh(categories, series2, color='blue', align='edge', height=+0.4)
axes1.set_axisbelow(True)
axes2.set_axisbelow(True)

axes1.grid(axis='x')
axes2.grid(axis='x')
plt.show()

matplotlib v. 3.2.2

【问题讨论】:

  • 在一个轴上绘制的所有内容(包括网格)总是或完全在另一轴上绘制的所有内容之前或之后。在您的情况下,唯一的解决方案是只为axes1 绘制一个网格,删除对另一个轴的网格的调用。
  • 您可以通过删除第二个轴上的网格来摆脱这种特定情况(也就是说,将axes2.grid(axis='x') 替换为axes2.grid(False))。但是,如果两个轴的网格不重叠,则渲染效果不佳。您可以在本主题中找到如何设置刻度:stackoverflow.com/questions/24943991/…
  • @JohanC 的评论完全正确,应该作为答案发布。

标签: python matplotlib


【解决方案1】:

在一个轴上绘制的所有内容(包括网格)总是或完全在另一轴上绘制的所有内容之前或之后。在您的情况下,唯一的解决方案是只为axes1 绘制一个网格,删除对另一个轴的网格的调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多