【问题标题】:How do I add space between the ticklabels and the axes in matplotlib如何在 matplotlib 中的刻度标签和轴之间添加空格
【发布时间】:2011-02-27 12:45:30
【问题描述】:

我已成功增加了刻度标签的字体,但现在它们离轴太近了。我想在刻度标签和轴之间添加一点呼吸空间。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:
    from matplotlib.cbook import get_sample_data
    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, axs = plt.subplots(3, 5, figsize=(8, 5), constrained_layout=True,
                            sharex=True, sharey=True)
    
    fname = get_sample_data('percent_bachelors_degrees_women_usa.csv',
                            asfileobj=False)
    gender_degree_data = np.genfromtxt(fname, delimiter=',', names=True)
    
    majors = ['Health Professions', 'Public Administration', 'Education',
              'Psychology', 'Foreign Languages', 'English',
              'Art and Performance', 'Biology',
              'Agriculture', 'Business',
              'Math and Statistics', 'Architecture', 'Physical Sciences',
              'Computer Science', 'Engineering']
    
    for nn, ax in enumerate(axs.flat):
        ax.set_xlim(1969.5, 2011.1)
        column = majors[nn]
        column_rec_name = column.replace('\n', '_').replace(' ', '_')
    
        line, = ax.plot('Year', column_rec_name, data=gender_degree_data, lw=2.5)
        ax.set_title(column, fontsize='small', loc='left', y=1.05)  # move the axes title
        ax.set_ylim([0, 100])
        ax.tick_params(axis='both', which='major', pad=15)  # move the tick labels
        ax.grid()
    
    fig.supxlabel('Year', y=-0.15)  # with adjusted position
    fig.supylabel('Percent Degrees Awarded To Women', x=-0.05)  # with adjusted position
    fig.suptitle('Majors', y=1.15)  # with adjusted position
    
    plt.show()
    

    【讨论】:

    • 不错的答案,特别是查看输出,这有助于我立即看到我需要的设置。与其在循环中保留样式,我发现设置一个样式文件很有用,比如ytick.major.pad: 5。 YMMV。
    【解决方案2】:

    如果您不想全局更改间距(通过编辑 rcParams),并且想要更简洁的方法,请尝试以下操作:

    ax.tick_params(axis='both', which='major', pad=15)

    或仅用于 x 轴

    ax.tick_params(axis='x', which='major', pad=15)

    或y轴

    ax.tick_params(axis='y', which='major', pad=15)

    【讨论】:

    • 这比遍历单个图的刻度要容易得多。谢谢!对于单轴,您还可以使用:ax.xaxis.set_tick_params(pad=n)
    • 对于没有经验的读者来说很难理解什么是斧头。如果我用 ax = plt.gca() 得到它,那么该命令只会移动标签。
    • 谢谢,这也适用于径向子图(为外部标签添加空间)
    • 要获取当前轴,您可能需要使用 plt.gca() 而不是 ax- plt.gca().tick_params(axis='both', which='major', pad= 15)
    【解决方案3】:

    看起来 matplotlib 将这些设置视为 rcParams:

    pylab.rcParams['xtick.major.pad']='8'
    pylab.rcParams['ytick.major.pad']='8'
    

    设置那些之前你创建任何数字,你应该没问题。

    我查看了源代码,似乎没有任何其他方式可以以编程方式设置它们。 (tick.set_pad() 看起来它试图做正确的事情,但填充似乎是在构造 Ticks 时设置的,之后无法更改。)

    【讨论】:

    • 在创建任何图形之前 不设置 rcParams,用户还可以使用上下文管理器:with plt.rc_context({"xtick.major.pad": 10}): 此行下方缩进的任何代码都将使用设置绘制在 rc_context 中指定。
    【解决方案4】:

    这可以使用set_pad 完成,但您必须重置标签...

    for tick in ax.get_xaxis().get_major_ticks():
        tick.set_pad(8.)
        tick.label1 = tick._get_text1()
    

    【讨论】:

    • 我建议这里的丑陋有点无关紧要,这仍然是一个很好的解决方案。在很多情况下,您不只是在同一个图形上绘制一个图。这意味着 rcParams 不是解决方案,因为您想避免全局设置。
    • @MikeGM:回想起来,我同意你提到的原因。我将把我的描述描述为丑陋,尽管标签重置并不完全优雅。感谢您的评论。
    • 不错的答案。一个“漂亮”的解决方案是拥有一个带有ytick.major.pad: 5.0axes.labelpad: 10.0 和其他相关设置的样式文件。然而,让它符合自己的口味会浪费许多宝贵的时间。
    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 2014-02-27
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 2015-10-28
    相关资源
    最近更新 更多