【问题标题】:Seaborn: How to specify plot minor ticks and gridlines in all plots when using lmplot?Seaborn:使用 lmplot 时如何在所有绘图中指定绘图次要刻度线和网格线?
【发布时间】:2021-02-28 06:37:07
【问题描述】:

在使用 lmplot 时,我正在尝试在所有绘图中绘制次要刻度线和网格线,使用以下代码:

sns.set(context="notebook", style='white', font_scale=2)

g=sns.lmplot(data=data ,
             x="x", 
             y="y",
             col="item",   # or use rows to display xplots in rows (one on top of the other)
             fit_reg=False,
             col_wrap=2,
             scatter_kws={'linewidths':1,'edgecolor':'black', 's':100}
            )

g.set(xscale='linear', yscale='log', xlim=(0,0.4), ylim=(0.01, 10000))

for ax in g.axes.flatten():
    ax.tick_params(axis='y', which='both', direction='out', length=4, left=True)
    ax.grid(b=True, which='both', color='gray', linewidth=0.1)
    
for axis in [ax.yaxis, ax.xaxis]:
    formatter = FuncFormatter(lambda y, _: '{:.16g}'.format(y))
    axis.set_major_formatter(formatter)

sns.despine()

g.tight_layout()

# Show the results
plt.show()

到目前为止,所有图中仅显示主要刻度线和网格线。

感谢您提供解决此问题的任何建议

【问题讨论】:

    标签: python matplotlib seaborn lmplot


    【解决方案1】:

    您的代码对我来说很好用。 我认为问题在于,当主要标签太大时,matplotlib 选择不显示次要刻度,因此不显示次要网格线。你可以改变font_scale,或者增加你的图的大小(见lmplot()中的height=

    考虑以下带有font_scale=1的代码

    tips = sns.load_dataset('tips')
    
    sns.set(context="notebook", style='white', font_scale=1)
    g = sns.lmplot(x="total_bill", y="tip", col="day", hue="day",
                   data=tips, col_wrap=2, height=3)
    
    g.set(xscale='linear', yscale='log')
    for ax in g.axes.flatten():
        ax.tick_params(axis='y', which='both', direction='out', length=4, left=True)
        ax.grid(b=True, which='both', color='gray', linewidth=0.1)
        
    for axis in [ax.yaxis, ax.xaxis]:
        formatter = matplotlib.ticker.FuncFormatter(lambda y, _: '{:.16g}'.format(y))
        axis.set_major_formatter(formatter)
    
    sns.despine()
    
    g.tight_layout()
    
    # Show the results
    plt.show()
    

    与使用font_scale=2的结果比较

    【讨论】:

    • 谢谢@Diziet Asahi,它现在可以工作了。谢谢你的详细解释
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多