【问题标题】:Stop x-axis labels from shrinking the plot in Matplotlib?阻止 x 轴标签缩小 Matplotlib 中的绘图?
【发布时间】:2019-02-26 22:35:06
【问题描述】:

我正在尝试使用以下代码制作条形图:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

test = {'names':['a','b','abcdefghijklmnopqrstuvwxyz123456789012345678901234567890'], 'values':[1,2,3]}
df = pd.DataFrame(test)

plt.rcParams['figure.autolayout'] = False
ax = sns.barplot(x='names', y='values', data=df)
ax.set_xticklabels(ax.get_xticklabels(), rotation=90)
plt.show()

但我收到以下错误,因为“名称”中的长值作为 x 轴上的标签使图像缩小,直到底部高于顶部。

Traceback (most recent call last):
  File "C:/Users/Adam/.PyCharm2018.2/config/scratches/scratch.py", line 11, in <module>
    plt.show()
  File "C:\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 253, in show
    return _show(*args, **kw)
  File "C:\Program Files\JetBrains\PyCharm 2018.2.3\helpers\pycharm_matplotlib_backend\backend_interagg.py", line 25, in __call__
    manager.show(**kwargs)
  File "C:\Program Files\JetBrains\PyCharm 2018.2.3\helpers\pycharm_matplotlib_backend\backend_interagg.py", line 107, in show
    self.canvas.show()
  File "C:\Program Files\JetBrains\PyCharm 2018.2.3\helpers\pycharm_matplotlib_backend\backend_interagg.py", line 62, in show
    self.figure.tight_layout()
  File "C:\Anaconda3\lib\site-packages\matplotlib\figure.py", line 2276, in tight_layout
    self.subplots_adjust(**kwargs)
  File "C:\Anaconda3\lib\site-packages\matplotlib\figure.py", line 2088, in subplots_adjust
    self.subplotpars.update(*args, **kwargs)
  File "C:\Anaconda3\lib\site-packages\matplotlib\figure.py", line 245, in update
    raise ValueError('bottom cannot be >= top')
ValueError: bottom cannot be >= top

如果我稍微减少该名称的长度,它看起来像这样:

如何让它扩大图形以适应标签而不是缩小轴?

【问题讨论】:

  • 可能这个答案是同一行,可能会帮助你stackoverflow.com/questions/22708888/…
  • omg...这是调用tight_layout的PyCharm内部后端...对此没有评论,除​​了...可能不使用pycharm。

标签: python-3.x matplotlib pycharm seaborn


【解决方案1】:

一种解决方法是自己创建Axes 实例作为轴,而不是作为子图。那么tight_layout() 没有任何作用,即使它是在内部调用的。然后,您可以将带有ax 关键字的Axes 传递给sns.barplot。现在的问题是,如果你调用plt.show(),标签可能会被截断,但如果你用bbox_inches='tight' 调用savefig,图形大小将被扩展为包含图形和所有标签:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])

test = {'names':['a','b','abcdefghijklmnopqrstuvwxyz123456789012345678901234567890'], 'values':[1,2,3]}
df = pd.DataFrame(test)

#plt.rcParams['figure.autolayout'] = False
ax = sns.barplot(x='names', y='values', data=df, ax=ax)
ax.set_xticklabels(ax.get_xticklabels(), rotation=90)
#plt.show()
fig.savefig('long_label.png', bbox_inches='tight')

声明:我没有pycharm,因此在这段代码中假设matplotlib 在有和没有pycharm 的情况下表现相同。无论如何,对我来说结果是这样的:

【讨论】:

  • 很好的解决方法!当xlabel 超过一定长度时,我在子图网格中获取imshow() 以使图像占据较大图形的整个宽度时遇到问题。这解决了它。谢谢。
【解决方案2】:

如果您想在交互式后端中使用它,除了手动调整图形大小之外,我没有找到任何其他方法。这就是我使用qt5agg 后端得到的结果:

ax = sns.barplot(x='names', y='values', data=df)
ax.set_xticklabels(ax.get_xticklabels(), rotation=90)
ax.figure.set_size_inches(5, 8)  # manually adjust figure size
plt.tight_layout()  # automatically adjust elements inside the figure
plt.show()

请注意,pycharm 的科学模式可能会做一些魔法来阻止它工作,因此您可能需要停用它或只在 pycharm 之外运行脚本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-24
    • 2020-10-15
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    相关资源
    最近更新 更多