【问题标题】:Add minor gridlines to matplotlib plot using seaborn使用 seaborn 向 matplotlib 图添加次要网格线
【发布时间】:2014-03-22 07:41:09
【问题描述】:

我是 Seaborn 软件包的粉丝,它使用 Matplotlib 制作漂亮的绘图。但我似乎无法弄清楚如何在我的图中显示次要网格线。

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sbn

x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

fig, ax = plt.subplots(1, 1)
ax.scatter(x, y)

ax.grid(b=True, which='major')
ax.grid(b=True, which='minor')

给予:

这里有什么想法吗?还有关于如何调整确实出现的 Seaborn 网格线样式的任何想法……特别是,我想让它们更窄。

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    将 CT Zhu 的回答与 tcaswell 的提示结合起来:

    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import seaborn as sbn
    
    x = np.linspace(0, 2 * np.pi, 100)
    y = np.sin(x)
    
    fig, ax = plt.subplots(1, 1)
    
    ax.scatter(x, y)
    ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.grid(b=True, which='major', color='w', linewidth=1.0)
    ax.grid(b=True, which='minor', color='w', linewidth=0.5)
    

    【讨论】:

    • 你能在 seaborn github 上打开一个关于这个的问题吗?您不需要自己设置次要网格线的样式,但我认为这是当前代码中的疏忽。
    【解决方案2】:

    那是因为次要刻度还没有定义,所以我们需要添加例如:

    ax.set_xticks(np.arange(0,8)-0.5, minor=True)
    ax.set_yticks([-1.25, -0.75, -0.25,0.24,0.75,1.25], minor=True)
    

    【讨论】:

    • 最好ax.get_xaxis().set_minor_locator(...)
    猜你喜欢
    • 2020-09-16
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    相关资源
    最近更新 更多