阻止 x 轴标签缩小 Matplotlib 中的绘图? [英] Stop x-axis labels from shrinking the plot in Matplotlib?

查看:61
本文介绍了阻止 x 轴标签缩小 Matplotlib 中的绘图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make a bar graph with the following code:

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 轴标签的名称"中的长值使图像缩小,直到底部高于顶部.

But I get the following error because the long value in 'names' as a label on the x-axis is making the image shrink until the bottom is above the top.

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

如果我稍微减少该名称的长度,它会是什么样子:

Here is what it looks like if I reduce the length of that name slightly:

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

How can I get it to expand the figure to fit the label instead of shrinking the axes?

推荐答案

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

One workaround is to create the Axes instance yourself as axes, not as subplot. Then tight_layout() has no effect, even if it's called internally. You can then pass the Axes with the ax keyword to sns.barplot. The problem now is that if you call plt.show() the label may be cut off, but if you call savefig with bbox_inches='tight', the figure size will be extended to contain both the figure and all labels:

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

PROCLAIMER:我没有 pycharm,所以在这段代码中假设,matplotlib 在有和没有 pycharm.无论如何,对我来说结果看起来像这样:

PROCLAIMER: I don't have pycharm, so there goes the assumption in this code, that matplotlib behaves the same with and without pycharm. Anyway, for me the outcome looks like this:

这篇关于阻止 x 轴标签缩小 Matplotlib 中的绘图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆