2017-06-29 155 views
3

seaborn.distplot(python3)を使用していて、各シリーズに2つのラベルが必要です。複数列の凡例を作成するpython seabornプロット

私はそうのようなハックストリングフォーマット方法を試みた:テキストは固定幅でコンソールで

# bigkey and bigcount are longest string lengths of my keys and counts 
label = '{{:{}s}} - {{:{}d}}'.format(bigkey, bigcount).format(key, counts['sat'][key]) 

を、Iを得る:

(-inf, 1) - 2538 
[1, 3)  - 7215 
[3, 8)  - 40334 
[8, 12) - 20833 
[12, 17) - 6098 
[17, 20) - 499 
[20, inf) -  87 

Iプロットで使用されるフォントを想定していますです固定幅ではないので、凡例に2列の列を持つラベルを指定する方法があるかどうかを知りたい場合は、label kwarg(または何でもよい)のtupleseaborn.distplotと呼んでください。

参照のための私のプロット:

enter image description here

はよさそうだが、私は本当に何とか揃えシリーズあたり2つのラベルをしたいです。

+1

あなたは伝説のための固定幅フォントを使用することができますか? – mwaskom

答えて

3

これは良い解決策ではありませんが、うまくいけば妥当な回避策です。重要なアイデアは、目的を整列させるために凡例を3列に分割し、2列目と3列目の凡例ハンドルを不可視にし、列3を右側に揃えることです。

import io 

import matplotlib 
import matplotlib.pyplot as plt 
import numpy as np 
import seaborn as sns 

x = np.random.randn(100) 
s = [["(-inf, 1)", "-", 2538], 
    ["[1, 3)", "-", 7215], 
    ["[3, 8)", "-", 40334], 
    ["[8, 12)", "-", 20833], 
    ["[12, 17)", "-", 6098], 
    ["[17, 20)", "-", 499], 
    ["[20, inf)", "-", 87]] 

fig, ax = plt.subplots() 
for i in range(len(s)): 
    sns.distplot(x - 0.5 * i, ax=ax) 

empty = matplotlib.lines.Line2D([0],[0],visible=False) 
leg_handles = ax.lines + [empty] * len(s) * 2 
leg_labels = np.asarray(s).T.reshape(-1).tolist() 
leg = plt.legend(handles=leg_handles, labels=leg_labels, ncol=3, columnspacing=-1) 
plt.setp(leg.get_texts()[2 * len(s):], ha='right', position=(40, 0)) 

plt.show() 

enter image description here

関連する問題