2017-06-23 17 views
0

2つのサブプロットを2つの異なる列を持つ2つのサブプロットから描画する必要があります。次の例のように、2つの列のすべてを含む共通の凡例を取得したい。パンダの異なる列を持つサブプロットのユニークな凡例を作成

d1 = pd.DataFrame({ #without one 
    'two' : [-1.,- 2.,- 3., -4.], 
    'three' : [4., 3., 2., 1.], 
    'four' : [4., 3., 4., 3.]}) 
tot_1=d1.sum(axis=1) 

d2 = pd.DataFrame({'one' : [1., 2., 3., 4.], 
    'two' : [4., 3., 3., 1.], 
    'three' : [-1., -1., -3., -4.], 
    'four' : [4., 3., 2., 1.]}) 

tot_2=d2.sum(axis=1) 


fig, ax = plt.subplots(nrows=2, ncols=1) 

#plot 1 
d1.plot.area(stacked=True,legend=False,ax=ax[0]) 
tot_1.plot(linestyle='-', color='black',legend=False,ax=ax[0]) 

###SECOND GRAPH#### 

ax3 = ax[1].twiny() 

#plot 2 
d2.plot.area(stacked=True,legend=False,ax=ax[1],sharex=ax[0]) 
tot_2.plot(linestyle='-',color='black',legend=False,ax=ax[1]) 

plt.show() 

enter image description here

PROBは列がちょうど二つのデータフレーム/プロットでは同じではないことである(同じである両方の一部ではない)と伝説がすべての列と持っていることを確認する必要があります2つのプロットの色と凡例が一致します。私はあなたが実際にパッチを色付けするcolumn-name:colorペアの辞書を使用することができます

+0

あなたがこの回答(編集したもの)を見たhttps://stackoverflow.com/a/31548279/1675954同様の(しかし異なる)ソリューションがここにありますhttps://stackoverflow.com/a/36532501/1675954 –

答えて

2

を渡すためにcol_name:colorで辞書を使用して、インスタンスのために、各列の色を選んだことができれば

(必要ではない)であっても良くはなりと後でそれから伝説を作ります。

import pandas as pd 
import matplotlib.pyplot as plt 

d1 = pd.DataFrame({ #without one 
    'two' : [-1.,- 2.,- 3., -4.], 
    'three' : [4., 3., 2., 1.], 
    'four' : [4., 3., 4., 3.]}) 
tot_1=d1.sum(axis=1) 

d2 = pd.DataFrame({'one' : [1., 2., 3., 4.], 
    'two' : [4., 3., 3., 1.], 
    'three' : [-1., -1., -3., -4.], 
    'four' : [4., 3., 2., 1.]}) 
tot_2=d2.sum(axis=1) 

columns = ["one", "two", "three", "four"] 
colors = dict(zip(columns, ["C"+str(i) for i in range(len(columns)) ])) 

fig, ax = plt.subplots(nrows=2, ncols=1) 

#plot 1 
d1.plot.area(stacked=True,legend=False,ax=ax[0], lw=0, 
      color=[colors[i] for i in d1.columns]) 
tot_1.plot(linestyle='-', color='black',legend=False,ax=ax[0]) 

###SECOND GRAPH#### 

ax3 = ax[1].twiny() 

#plot 2 
d2.plot.area(stacked=True,legend=False,ax=ax[1],sharex=ax[0], lw=0, 
      color=[colors[i] for i in d2.columns]) 
tot_2.plot(linestyle='-',color='black',legend=False,ax=ax[1]) 

labels = list(set(list(d1.columns) + list(d2.columns))) 

handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels] 
ax3.legend(handles=handles, labels=labels) 
plt.show() 

enter image description here

関連する問題