阻止x轴标签缩小Matplotlib中的图?

时间:2018-09-23 00:29:47

标签: python-3.x matplotlib pycharm seaborn

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

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()

但是我收到以下错误消息,因为'names'中的long值作为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

如果我稍微减少该名称的长度,则如下所示: enter image description here

我如何才能扩大图形以适合标签而不是缩小轴?

2 个答案:

答案 0 :(得分:1)

一种解决方法是将您自己的Axes实例创建为 axes ,而不是子图。这样tight_layout()无效,即使在内部调用也是如此。然后,您可以将带有Axes关键字的ax传递给sns.barplot。现在的问题是,如果您调用plt.show(),则标签可能会被切断,但是如果您使用savefig调用了bbox_inces='tight',则图形尺寸将被扩展为既包含图形又包含所有标签:

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的情况下都表现相同。无论如何,对我来说结果看起来像这样:

result of above code

答案 1 :(得分:0)

如果您想在交互式后端中使用此工具,除了手动调整图形尺寸外,没有其他方法。这是我使用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()

enter image description here

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