【问题标题】:How to increase the font size of the legend in my Seaborn plot?如何在我的 Seaborn 图中增加图例的字体大小?
【发布时间】:2017-12-06 10:04:32
【问题描述】:

我有以下代码来创建 Seaborn 条形图。我很难弄清楚如何增加情节中出现的图例的字体大小。

g=sns.stripplot(x="Market", y="Rate", hue="Group",data=myBenchmarkData, jitter=True, size=12, alpha=0.5)
g.axes.set_title("4* Rate Market and by Hotel Groups for Year 2016",fontsize=25)
g.set_xlabel("Market",fontsize=20)
g.set_ylabel("Rate (in EUR)",fontsize=20)
g.tick_params(labelsize=15)
plt.savefig ('benchmark1.png')

我的 x 轴和 y 轴标签字体大小没问题,但我的情节中图例的字体大小很小。怎么改?

【问题讨论】:

    标签: python matplotlib legend seaborn


    【解决方案1】:

    按照本例使用matplotlib函数setp

    import seaborn as sns
    import matplotlib.pylab as plt
    sns.set_style("whitegrid")
    tips = sns.load_dataset("tips")
    
    ax = sns.stripplot(x="sex", y="total_bill", hue="day", data=tips, jitter=True)
    plt.setp(ax.get_legend().get_texts(), fontsize='22') # for legend text
    plt.setp(ax.get_legend().get_title(), fontsize='32') # for legend title
    
    plt.show()
    

    另一种方法是将所有图形的font_scale 更改为plotting_contexthttp://seaborn.pydata.org/generated/seaborn.plotting_context.html

    【讨论】:

    • 如何使用因子图做到这一点?我收到错误:AttributeError: 'FacetGrid' object has no attribute 'get_legend'.
    • 但是如何使图例中的标记大小与图中的标记大小匹配?
    • @Archie FacetGrid 对象在其_legend 属性中有一个图例。因此,您可以使用 setp(g._legend.get_title(), fontsize=32) 更改它。
    【解决方案2】:

    今天有一个更简单的方法来做到这一点,只需设置你的身材,然后调用

    plt.legend(fontsize='x-large', title_fontsize='40')
    

    https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html

    可能取决于您使用的 matplotlib 版本。我使用的是 2.2.3,它有 fontsize 参数,但没有 title_fontsize

    【讨论】:

      猜你喜欢
      • 2018-10-16
      • 2019-11-25
      • 2013-12-22
      • 2010-12-04
      • 2021-01-07
      • 2021-03-11
      • 1970-01-01
      • 2011-05-13
      相关资源
      最近更新 更多