[英]matplotlib - wrap text in legend
我目前正在尝试通过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')
有什么方法可以设置图例条目以换行,无论是字符还是长度? 我尝试使用textwrap
重命名DataFrame列,然后再进行如下绘制:
import textwrap
[...]
renames = {c: textwrap.fill(c, 15) for c in df.columns}
df.rename(renames, inplace=True)
[...]
但是, pandas
似乎忽略了列名中的换行符。
您可以使用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()
这使:
更新:正如评论中指出的那样, 文档说textwrap.fill()
是'\\n'.join(wrap(text, ...))
简写。 因此,您可以改为使用:
from textwrap import fill
labels = [fill(l, 20) for l in df.columns]
正如@Jan Zeiseweis提到的,您可以在文本中使用\\ n任意次(例如“更长,\\ n更不方便,\\ n讨厌的图例标签”),如果您对此灵活,则可以放置图例通过指定2列,可以在该图下方获得更好的可视化效果:
ax.legend(bbox_to_anchor=(0.9, -0.15),ncol=2,fontsize=8)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.