2017-11-01 546 views
3

pandasのデータをmatplotlib/seabornでプロットしようとしていますが、私の欄のタイトルの1つが特に長く、プロットが広がっています。次の例を考えてみましょう:matplotlib - 凡例のテキストを折り返し

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

は、私はどちらかの文字や長さに、ラップに凡例を設定することができます任意の方法はありますか?私は前にそうようにプロットするデータフレームの列の名前を変更するtextwrapを使用しようとしました:

import textwrap 
[...] 
renames = {c: textwrap.fill(c, 15) for c in df.columns} 
df.rename(renames, inplace=True) 
[...] 

しかし、pandasは、列名に改行を無視するように見えました。

+0

あなたは、単純には「\ n」を私が簡略化されてきた –

+0

@JanZeiseweisを追加することができます私が見ているデータはCSVファイルから来ています – asongtoruin

答えて

2

textwrap.wrapを使用すると、凡例のエントリを調整することができます(this answer)。これを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() 

enter image description here

を更新:コメントで指摘したように、documentationtextwrap.fill()'\n'.join(wrap(text, ...))の略記であると言います。したがって、あなたの代わりに使用することができます。

from textwrap import fill 
labels = [fill(l, 20) for l in df.columns] 
+0

これは良い答えですが、[docs](https:// docs。 python.org/2/library/textwrap.html)は、 '' fill() 'は' '\ n' .join(wrap(text、...)) ''の省略形です。これを反映するためにあなたの答えを更新できるなら、私はそれを答えたものとしてマークします。 – asongtoruin

+0

これを指摘してくれてありがとう、私はもっと慎重にドキュメントを読む必要があります:) – DavidG

0

@Jan Zeiseweisが希望どおりに例えば(\ nはテキスト内で何度でも使用することができます述べたように「ずっと長く、\ nははるかに不便、\ nは迷惑な伝説のレーベル」 ) そして、あなたはこれに柔軟であれば、あなたが2列を指定することで、より良い可視化を得るために、図の下の凡例を置くことができます。

ax.legend(bbox_to_anchor=(0.9, -0.15),ncol=2,fontsize=8) 
+0

私はコメントで述べたように、私の実際のデータはcsvファイルから来るので、私は手動で列名を編集したくありません。 – asongtoruin

関連する問題