【问题标题】:Draw minor grid lines below major gridlines在主要网格线下方绘制次要网格线
【发布时间】:2015-07-05 02:45:35
【问题描述】:

我正在尝试使用 matplotlib 绘制网格。网格的 zorder 应该在图中所有其他线的后面。到目前为止,我的问题是 次要网格线始终绘制在主要网格线之前,即

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

plt.rc('text', usetex=True)
plt.rc('font', family='serif')

f = plt.figure(figsize=(4,4))
ax = f.add_subplot(111)

ax.xaxis.set_minor_locator(MultipleLocator(1))
ax.xaxis.set_major_locator(MultipleLocator(10))
ax.yaxis.set_minor_locator(MultipleLocator(1))
ax.yaxis.set_major_locator(MultipleLocator(10))

majc ="#3182bd"
minc ="#deebf7"

ax.xaxis.grid(True,'minor',color=minc, ls='-', lw=0.2)
ax.yaxis.grid(True,'minor',color=minc, ls='-', lw=0.2)
ax.xaxis.grid(True,'major',color=majc, ls='-')
ax.yaxis.grid(True,'major',color=majc,ls ='-')
ax.set_axisbelow(True)

x = np.linspace(0, 30, 100)
ax.plot(x, x, 'r-', lw=0.7)

[line.set_zorder(3) for line in ax.lines]
plt.savefig('test.pdf')

有什么建议吗?谢谢。

编辑:特写示例

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    更具体地说,它看起来像是按顺序绘制垂直主要、垂直次要、水平主要、水平次要和绘制的线。可能对 matplotlib 基础非常深入。

    对于您使用的颜色,您可以通过 alpha 而不是 RGB 来区分主要和次要颜色。更改示例的两行:

    ax.xaxis.grid(True,'minor',color=majc, alpha=0.2, ls='-', lw=0.2)
    ax.yaxis.grid(True,'minor',color=majc, alpha=0.2, ls='-', lw=0.2)
    

    结果:

    【讨论】:

    • 这种方法的问题是 pdf 不支持透明度还是我错了?谢谢你的回复
    • 我保存为 pdf,这就是我得到的结果(实际上只更改了我显示的两行)。如果 pdf 不处理透明度,则“扁平化”算法正在正确处理颜色。
    • 看来你是对的。我认为您的回复是一个很好的解决方法,但很高兴知道 maplotlib api 中出了什么问题以及如何解决它。
    • 我不是 matplotlib 开发人员,但我认为这可能是内部错误,是的; ax.xaxis.grid 的文档字符串说“ kwargs 用于设置网格的线属性”,但我无法使用任何一组 zorder 值获得顶部/第二个绘制的垂直网格线我试过了。
    • @cphlewis。真可惜。我可能不得不将此作为一个单独的问题提出。我发现有一个非常适合我的角落案例。当您使用 SVG 从 LibreOffice 创建 PDF 时,如果 SVG 中有透明度,某些 PDF 阅读器(如 Acrobat)会崩溃。
    猜你喜欢
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多