有一个类似的问题 - 但我不能让那里提出的解决方案有效.
这是一个带有长标题的示例图:
#!/usr/bin/env python
import matplotlib
import matplotlib.pyplot
import textwrap
x = [1,2,3]
y = [4,5,6]
# initialization:
fig = matplotlib.pyplot.figure(figsize=(8.0, 5.0))
# lines:
fig.add_subplot(111).plot(x, y)
# title:
myTitle = "Some really really long long long title I really really need - and just can't - just can't - make it any - simply any - shorter - at all."
fig.add_subplot(111).set_title("\n".join(textwrap.wrap(myTitle, 80)))
# tight:
(matplotlib.pyplot).tight_layout()
# saving:
fig.savefig("fig.png")
Run Code Online (Sandbox Code Playgroud)
它给了一个
AttributeError: 'module' object has no attribute 'tight_layout'
Run Code Online (Sandbox Code Playgroud)
如果我 …
我目前正在尝试pandas
通过matplotlib
/绘制一些数据seaborn
,但是我的一个专栏标题特别长并且延伸了情节。考虑以下示例:
import random
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('darkgrid')
random.seed(22)
fig, ax = plt.subplots()
df = pd.DataFrame({'Year': [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016],
'One legend label': [random.randint(1,15) for _ in range(10)],
'A much longer, much more inconvenient, annoying legend label': [random.randint(1, 15) for _ in range(10)]})
df.plot.line(x='Year', ax=ax)
ax.legend(bbox_to_anchor=(1, 0.5))
fig.savefig('long_legend.png', bbox_inches='tight')
Run Code Online (Sandbox Code Playgroud)
有什么方法可以将图例条目设置为在字符或长度上换行?textwrap
在绘制之前,我尝试使用重命名 DataFrame 列,如下所示:
import textwrap
[...]
renames = …
Run Code Online (Sandbox Code Playgroud) 我正在尝试绘制带有长 x 标签字符串的图表。这篇文章描述了一个类似的问题(如何使用 自动换行 y 轴标签tight_layout
),但对我来说不起作用,因为tight_layout
改变了比例。另一篇文章描述了一种无法实现轴标签自动换行的方法 - 该包textwrap
需要指定要换行的字符数。
我的代码:
import matplotlib.pyplot as plt
plt.figure()
plt.bar([0,1,2,3],[0,1,4,9])
labels = ['superdupersuperduperlonglabel0','superdupersuperduperlonglabel1',
'superdupersuperduperlonglabel2','superdupersuperduperlonglabel3']
plt.xticks([0,1,2,3],labels, wrap = True)
plt.show()
Run Code Online (Sandbox Code Playgroud)
这是结果图,x 标签重叠:
根据 matplotlib 文档:
文本属性可用于控制标签的外观。
但wrap = True
似乎没有正确包装 x 标签。有什么建议吗?
我有很长的绘图刻度标签,不幸的是我无法缩短。因此,我正在寻找将标签拆分为多行(换行文本)的代码。我尝试了文本换行,但它导致我的代码出现错误。将刻度标签设置为rotation=0
会使刻度标签相互重叠并变得不可读。
我也尝试过使用一个rotation=90
,但刻度标签却溢出到我的图表空间中。
plt.title(param)
plt.ylabel('Measurement')
plt.xticks(x_axis, labels, rotation = 10, fontsize=8, horizontalalignment="center")
plt.tick_params(axis='x', pad=6)
lgd = ax.legend(loc = 'upper left', bbox_to_anchor=(1,1))
Run Code Online (Sandbox Code Playgroud)