2016-07-14 12 views
2

私はこれに従うようにしてきましたHow to make custom legend in matplotlibですが、いくつかのことが紛失していると思います。私は私のプロットでポイントの異なるクラスのためのカスタムカラーマッピングを使用し、それらのカラーラベルのペアでテーブルを置くことができるようにしたい。情報を辞書D_color_labelに保存してから、2つのパラレルリストcolorslabelsを作成しました。私はax.legendでそれを使用しようとしましたが、うまくいかないようです。Seaborn regplot(Python 3)のカスタムレジェンド

np.random.seed(0) 

# Create dataframe 
DF_0 = pd.DataFrame(np.random.random((100,2)), columns=["x","y"]) 

# Label to colors 
D_idx_color = {**dict(zip(range(0,25), ["#91FF61"]*25)), 
       **dict(zip(range(25,50), ["#BA61FF"]*25)), 
       **dict(zip(range(50,75), ["#916F61"]*25)), 
       **dict(zip(range(75,100), ["#BAF1FF"]*25))} 

D_color_label = {"#91FF61":"label_0", 
       "#BA61FF":"label_1", 
       "#916F61":"label_2", 
       "#BAF1FF":"label_3"} 

# Add color column 
DF_0["color"] = pd.Series(list(D_idx_color.values()), index=list(D_idx_color.keys())) 

# Plot 
fig, ax = plt.subplots(figsize=(8,8)) 
sns.regplot(data=DF_0, x="x", y="y", scatter_kws={"c":DF_0["color"]}, ax=ax) 

# Add custom legend 
colors = list(set(DF_0["color"])) 
labels = [D_color_label[x] for x in set(DF_0["color"])] 

# If I do this, I get the following error: 
# ax.legend(colors, labels) 
# UserWarning: Legend does not support '#BA61FF' instances. 
# A proxy artist may be used instead. 

enter image description here

答えて

2

あなたが標識されるであろう伝説関数アーティストに配置する必要がありhttp://matplotlib.org/users/legend_guide.htmlによります。個別にあなたはすべてのアーティストのために独自のラベルを設定するために、個別に色やプロットして、データによってグループに1つの色のすべてのデータを持っているscatter_plotを使用するには:

import pandas as pd 
import numpy as np 
import matplotlib.pylab as plt 
import seaborn as sns 

np.random.seed(0) 

# Create dataframe 
DF_0 = pd.DataFrame(np.random.random((100,2)), columns=["x","y"]) 
DF_0['color'] = ["#91FF61"]*25 + ["#BA61FF"]*25 + ["#91FF61"]*25 + ["#BA61FF"]*25 
#print DF_0 

D_color_label = {"#91FF61":"label_0", 
       "#BA61FF":"label_1", 
       "#916F61":"label_2", 
       "#BAF1FF":"label_3"} 
colors = list(set(DF_0["color"])) 
labels = [D_color_label[x] for x in set(DF_0["color"])] 

ax = sns.regplot(data=DF_0, x="x", y="y", scatter_kws={'c':DF_0['color'], 'zorder':1}) 

# Make a legend 
# groupby and plot points of one color 
ind = 0 
for i, grp in DF_0.groupby(['color']): 
    grp.plot(kind = 'scatter', x = 'x', y = 'y', c = i, ax = ax, label = labels[ind], zorder = 0) 
    ind += 1  
ax.legend(loc=2) 

plt.show() 

enter image description here

関連する問題