【问题标题】:Reduce the xticklabels area in a matplotlib figure减少 matplotlib 图中的 xticklabels 区域
【发布时间】:2017-10-18 15:32:02
【问题描述】:

我的 x 轴刻度标签(下图)正在从整体图中窃取宝贵的空间。我试图通过更改文本旋转来减小它的大小,但这并没有多大帮助,因为文本标签很长。

有没有更好的方法来减少 xticklabel 区域占用的空间?例如,我可以在栏内显示此文本吗?感谢您的支持。

我的图表设置代码是:

import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.sans-serif'] = "Century Gothic"
matplotlib.rcParams['font.family'] = "Century Gothic"

ax = df1.plot.bar(x = '', y = ['Events Today', 'Avg. Events Last 30 Days'], rot = 25, width=0.8 , linewidth=1, color=['midnightblue','darkorange'])

for item in ([ax.xaxis.label, ax.yaxis.label] +
         ax.get_xticklabels() + ax.get_yticklabels()):
    item.set_fontsize(15)

ax.legend(fontsize = 'x-large', loc='best')
plt.tight_layout()
ax.yaxis.grid(True, which='major', linestyle='-', linewidth=0.15)
ax.set_facecolor('#f2f2f2')
plt.show()

【问题讨论】:

  • 问题的minimal reproducible example 怎么样?
  • ?!提供描述、代码、打印..
  • 你是在问我或任何愿意回答这个问题的人来自己产生一些df1。鉴于您是在这里寻求帮助的人,这对您不太好。
  • 我不是问你什么,如果你不想帮助就不要帮助。
  • 您肯定需要添加一些示例数据。如果没有,我要做的就是将您链接到 matplotlib 开发版本的文档中的教程:matplotlib.org/devdocs/tutorials/intermediate/…

标签: python matplotlib plot axis-labels


【解决方案1】:

当我最终得到不美观的长 xticklabels 时,我要做的第一件事也是最重要的事情是尝试缩短它们。这似乎很明显,但值得指出的是,使用缩写或不同的描述通常是最简单和最有效的解决方案。

如果您遇到长名称和特定字体大小的问题,我建议您改为制作水平条形图。我通常更喜欢带有较长标签的水平图,因为它更容易阅读未旋转的文本(这也可以进一步减少字体大小)添加换行符也会有所帮助。

这是一个带有笨拙标签的图表示例:

import pandas as pd
import seaborn as sns # to get example data easily

iris = sns.load_dataset('iris')
means = iris.groupby('species').mean()
my_long_labels = ['looooooong_versicolor', 'looooooooog_setosa', 'looooooooong_virginica']
# Note the simpler approach of setting fontsize compared to your question
ax = means.plot(kind='bar', y=['sepal_length', 'sepal_width'], fontsize=15, rot=25)
ax.set_xlabel('')
ax.set_xticklabels(my_long_labels)

我会将其更改为水平条形图:

ax = means.plot(kind='barh', y=['sepal_length', 'sepal_width'], fontsize=15)
ax.set_ylabel('')
ax.set_yticklabels(my_long_labels)

您可以在标签中引入换行符以进一步提高可读性:

ax = means.plot(kind='barh', y=['sepal_length', 'sepal_width'], fontsize=15, rot=0)
ax.set_ylabel('')
ax.set_yticklabels([label.replace('_', '\n') for label in my_long_labels])

这也适用于竖线:​​

ax = means.plot(kind='bar', y=['sepal_length', 'sepal_width'], fontsize=15, rot=0)
ax.set_xlabel('')
ax.set_xticklabels([label.replace('_', '\n') for label in my_long_labels])

最后,您也可以将文本放在条内,但这很难阅读。

ax = means.plot(kind='barh', y=['sepal_length', 'sepal_width'], fontsize=15)
ax.set_ylabel('')
ax.set_yticklabels(my_long_labels, x=0.03, ha='left', va='bottom')

【讨论】:

  • 太棒了!感谢您提供如此完整的答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 2011-09-14
  • 1970-01-01
  • 2011-05-01
  • 1970-01-01
相关资源
最近更新 更多