matplotlib - 在图例中包装文本

aso*_*uin 8 python matplotlib pandas

我目前正在尝试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 = {c: textwrap.fill(c, 15) for c in df.columns}
df.rename(renames, inplace=True)
[...]
Run Code Online (Sandbox Code Playgroud)

但是,pandas似乎忽略了列名中的换行符。

Dav*_*idG 11

您可以使用textwrap.wrap来调整您的图例条目(在这个答案中找到),然后在调用中更新它们ax.legend()

import random
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from textwrap import wrap

sns.set_style('darkgrid')

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)]})

random.seed(22)
fig, ax = plt.subplots()

labels = [ '\n'.join(wrap(l, 20)) for l in df.columns]

df.plot.line(x='Year', ax=ax,)
ax.legend(labels, bbox_to_anchor=(1, 0.5))

plt.subplots_adjust(left=0.1, right = 0.7)
plt.show()
Run Code Online (Sandbox Code Playgroud)

这使:

在此处输入图片说明

更新:正如评论中所指出的,文档textwrap.fill()'\n'.join(wrap(text, ...)). 因此,您可以改为使用:

from textwrap import fill
labels = [fill(l, 20) for l in df.columns]
Run Code Online (Sandbox Code Playgroud)