我目前在尝试通过matplotlib
/seaborn
绘制一些pandas
数据,但我的某个列标题特别长,使得图表变得很长。请考虑以下示例:
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')
这将生成以下图表:
![graph with wide legend](https://istack.dev59.com/AW5Hr.webp)
textwrap
在绘图之前重命名DataFrame列,如下所示:import textwrap
[...]
renames = {c: textwrap.fill(c, 15) for c in df.columns}
df.rename(renames, inplace=True)
[...]
不过,pandas
似乎忽略了列名称中的换行符。