2017-07-06 3 views
1

私は以前の解決策を読みましたが、それらのいずれかを動作させることはできませんでした。私は、個々のサブプロットのためのグローバルな伝説を持っていたい。おおよそこのような事前に定義されたクラスのうち このサブプロットのための斧オブジェクトが事前定義された関数「get_plot」によって生成される 「The_predefined_plotting_class」:内容の異なるサブプロットのグローバルな凡例

My code

機能は斧オブジェクトを返し、各AXオブジェクトは複数を有します元の "データファイル"の複数の列からの "プロット"/

enter image description here

をグローバルな伝説を作るために:私は私が使用できることを読んで、このサイトで見つけた解決策の一つで

。残念ながら、私はどのように個々のaxオブジェクト(またはその中のデータ)をハンドルに追加してこの作業を行うか分かりません。 各プロットには、いくつかの同一の列名が含まれています。エントリ/名前が多くのサブプロットに存在する場合は、一度だけ印刷する必要があります。

Solution1

Solution2

Solution3

EDIT

私は私がやった写真を利用しましたが、どんなことを本当に申し訳なく思って、私は私のコードをポストすることはできませんでしたwebsideそれでもプレビューウィンドウに正しく表示されました(このスクリーンショットはこのウィンドウからのものです)

EDIT2

私はこのようにそれを行う場合:

lines=[] 
labels=[] 
for idata, datafile in enumerate(datafiles): 

    MYData = The_predefined_plotting_class.from_file(datafile) 

    axis[idata] = The_predefined_plotting_class.get_plot(*kwargs) 
    h, l = axis[idata].get_legend_handles_labels() 

    lines.append(h) 
    labels.append(l) 


LINES=[] 
LABELS=[] 
for i in range(0, nrows): 
    LINES+=lines[i] 
    LABELS+=labels[i] 
plt.legend(LINES, LABELS, loc="upper left", bbox_to_anchor=[0, 1],ncol=3, shadow=True, title="Legend", fancybox=True) 
plt.show() 

その後、それは、すべてのデータを示しています。データの中には、同じ行とラベルのハンドラがあります。両方のリストを繰り返し処理する問題が残っています。両方のリストにタプル(LINES [j]; LABELS [j])=(LINES [i]; LABELS [i])二度存在する(そしてその時のみ)。好ましくは最初のエントリ:

EDIT3

labels =[] 
lines = [] 
h=["Cat","Mouse","Dog","Cat","Cat","Kangaroo","Dog"] 
l=["black","white","brown","white","black","yellow","brown"] 


for handle, label in zip(h, l): 
    if label not in labels : 

      lines.append(handle) 
      labels.append(label) 

print "The disired Output is :"    
print '["Cat","Mouse","Dog","Cat","Kangaroo"]' 
print '["black","white","brown","white","yellow"]' 

print "currently you get:"    

print lines 
print labels 

EDIT4

は、私は私の実際のデータで発生するすべての可能な状況が含まれている必要があり、 "最小" 作業例を追加します。

lines=[] 
labels=[] 
legend_properties = {'weight':'bold','size':10} 
# Example data 
x1 = np.linspace(0.0, 5.0) 
x2 = np.linspace(0.0, 2.0) 

a = np.cos(2 * np.pi * x1) * np.exp(-x1) 
b = np.cos(2 * np.pi * x2) 
c = np.cos(5 * np.pi * x1) * np.exp(-x1) 
c2 = np.cos(5 * np.pi * x1**2) * np.exp(-x1) 
d = np.cos(2 * np.pi * x2) 
d2 = np.cos(2 * np.pi * x2-1) 
e = x1*5 
e2 = -x1*5 
f = np.exp(x1)-e 
f2 = (np.exp(x1)-e)/2 

nrows = 4 
# Plot 

fig, axis = plt.subplots(nrows, sharex=True, sharey=False, figsize=(5, 8)) 
fig.subplots_adjust(hspace=0.0001) 
fig.suptitle("Stacked Plots with global Legend wich contains to little elements",fontsize=14,weight='bold') 



axis[0].plot(x1, e, 'k--', label='Label1',color="green") 
axis[0].plot(x1, e2, 'k--', label='Label2',color="blue") 
axis[0].plot(x1, a, 'k--', label='Label3',color="yellow") 
axis[1].plot(x1, c, 'k--', label='Label1',color="green") 
axis[1].plot(x1, c2, 'k--', label='Label2',color="blue") 
axis[1].plot(x1, a, 'k--', label='Label3',color="grey") 
axis[2].plot(x2, d, '*', label='Label1',color="green") 
axis[2].plot(x2, d2, 'D', label='Label2',color="green") 
axis[3].plot(x1, f, 'H', label='Label1',color="green") 
axis[3].plot(x1, f2, 'D', label='Label2',color="green") 

for i in range(nrows): 
    h, l = axis[i].get_legend_handles_labels() 
    for handle, label in zip(h, l): 
     if label not in labels: 
      lines.append(handle) 
      labels.append(label) 

# only 3 Legend entrys Label1 , Label2 and Label3 are visible .. Differences in cloors and markers are ignored 
plt.legend(handles=lines, labels=labels,bbox_to_anchor=(0., nrows+.02, 1., .102), loc=3,ncol=3, prop=legend_properties,mode="expand", borderaxespad=0.,frameon=False,framealpha=0.0) 

plt.show() 

EDIT5

これは、実際のプロットが生成される問題のスクリプトのフォーム部分です。 「列」には、実際に描画されるデータの名前だけが含まれます。

EDIT6

# add plots 
    ic = 0 
    for col in columns: 
     if col == "envelope": 
      ax.plot(self.data.index, self.data.envelope, 
        linewidth=LINEWIDTH_envelope, c=last_color, label="") 
     elif col == "Exp": 
      ax.plot(self.data.index, self.data.Exp, c=first_color, linestyle="", 
        label="Exp", marker="o", markersize=MARKERSIZE) 
     else: 
      color = used_colors[ic % len(used_colors)] 
      if fill and "BG" in self.data.columns: 
       ax.fill_between(self.data.index, self.data.BG, 
           self.data[col], label=col, alpha=ALPHA, 
           color=color) 
      else: 
       ax.plot(self.data.index, self.data[col], linewidth=LINEWIDTH, 
         c=color, label=col) 
      ic += 1 
は、私は私がここで紹介するという考えに基づいて解決策を見つけることを試みた:

Iteration though lists

残念ながら何のために動作しない文字列を含む二つのリストのために働きますアーティストhandelsそれは思われる。

import matplotlib.pyplot as plt 
import numpy as np 
LI=[] 
lines=[] 
labels=[] 
legend_properties = {'weight':'bold','size':10} 
# Example data 
x1 = np.linspace(0.0, 5.0) 
x2 = np.linspace(0.0, 2.0) 

a = np.cos(2 * np.pi * x1) * np.exp(-x1) 
b = np.cos(2 * np.pi * x2) 
c = np.cos(5 * np.pi * x1) * np.exp(-x1) 
c2 = np.cos(5 * np.pi * x1**2) * np.exp(-x1) 
d = np.cos(2 * np.pi * x2) 
d2 = np.cos(2 * np.pi * x2-1) 
e = x1*5 
e2 = -x1*5 
f = np.exp(x1)-e 
f2 = (np.exp(x1)-e)/2 

nrows = 4 
# Plot 

fig, axis = plt.subplots(nrows, sharex=True, sharey=False, figsize=(5, 8)) 
fig.subplots_adjust(hspace=0.0001) 
#fig.suptitle("Stacked Plots with global Legend wich contains to little elements",fontsize=14,weight='bold') 



axis[0].plot(x1, e, 'k--', label='Label1',color="green") 
axis[0].plot(x1, e2, 'k--', label='Label2',color="blue") 
axis[0].plot(x1, a, 'k--', label='Label3',color="yellow") 
axis[1].plot(x1, c, 'k--', label='Label1',color="green") 
axis[1].plot(x1, c2, 'k--', label='Label2',color="blue") 
axis[1].plot(x1, a, 'k--', label='Label3',color="grey") 
axis[2].plot(x2, d, '*', label='Label1',color="green") 
axis[2].plot(x2, d2, 'D', label='Label2',color="green") 
axis[3].plot(x1, f, 'H', label='Label1',color="green") 
axis[3].plot(x1, f2, 'D', label='Label2',color="green") 

for i in range(nrows): 
    print i 
    h, l = axis[i].get_legend_handles_labels() 
    for hl in zip(h,l): 

     if hl not in LI: 
      LI.append(hl) 
      lines.append(LI[-1][0]) 
      labels.append(LI[-1][1]) 

print LI    
















# only 3 Legend entrys Label1 , Label2 and Label3 are visible .. Differences in cloors and markers are ignored 
plt.legend(handles=lines, labels=labels,bbox_to_anchor=(0., nrows+.02, 1., .102), loc=3,ncol=3, prop=legend_properties,mode="expand", borderaxespad=0.,frameon=False,framealpha=0.0) 


plt.show() 

私はこの問題は、メモリアドレスのための唯一の文字列が

if hl not in LI: 

ない「H」の実際の内容で比較されていることだと思いますか?私は両方のmatplotlib.collections.PolyCollection持っている)とmatplotlib.lines.Line2Dとして私の実際のデータをよりよく反映されている。ここ

import matplotlib.pyplot as plt 
import numpy as np 
import matplotlib.mlab as mlab 
import math 
import matplotlib.collections 

def is_inlist(handle, handles): 
    for h in handles: 
     if isinstance(handle, matplotlib.collections.PolyCollection) and isinstance(h, matplotlib.collections.PolyCollection): 
      if np.all(h.get_facecolor() == handle.get_facecolor()) and \ 
       np.all(h.get_linestyle() == handle.get_linestyle()) and \ 
       np.all(h.get_alpha() == handle.get_alpha()): 
       return True 
     if isinstance(handle, matplotlib.lines.Line2D) and isinstance(h, matplotlib.lines.Line2D): 
      if h.get_color() == handle.get_color() and \ 
       h.get_linestyle() == handle.get_linestyle() and \ 
       h.get_marker() == handle.get_marker(): 
       return True   


    return False 


lines=[] 
labels=[] 
legend_properties = {'weight':'bold','size':10} 
# Example data 


mu = 0 
mu2 = 5 
variance = 1 
variance2 = 2 
sigma = math.sqrt(variance) 
sigma2 = math.sqrt(variance2) 
x = np.linspace(mu-3*variance,mu+3*variance, 100) 
x2 = np.linspace(mu2-3*variance2,mu2+3*variance2, 100) 

nrows = 4 
# Plot 

fig, axis = plt.subplots(nrows, sharex=True, sharey=False, figsize=(5, 8)) 
fig.subplots_adjust(hspace=0.0001) 
#fig.suptitle("Stacked Plots with global Legend wich contains to little elements",fontsize=14,weight='bold') 


axis[0].fill_between(x+6,0,mlab.normpdf(x, mu, sigma), color='green',alpha=0.5,label="PEAK1", interpolate=True) 
axis[0].fill_between(x+4,0,mlab.normpdf(x, mu, sigma), color='orange',alpha=0.5,label="PEAK2", interpolate=True) 
axis[0].fill_between(x+3,0,mlab.normpdf(x, mu, sigma), color='blue',alpha=0.5,label="PEAK3", interpolate=True) 
axis[0].fill_between(x+7,0,mlab.normpdf(x, mu, sigma), color='red',alpha=0.5,label="PEAK4", interpolate=True) 
axis[0].plot(x2,2.5*mlab.normpdf(x2, mu2, sigma2),color='black',linestyle="",label="Exp", marker="o", markersize=4) 

axis[1].fill_between(x+6,0,mlab.normpdf(x, mu, sigma), color='green',alpha=0.5,label="PEAK1", interpolate=True) 
axis[1].fill_between(x+4,0,mlab.normpdf(x, mu, sigma), color='purple',alpha=0.5,label="PEAK2", interpolate=True) 
axis[1].fill_between(x+3,0,mlab.normpdf(x, mu, sigma), color='blue',alpha=0.5,label="PEAK3", interpolate=True) 
axis[1].fill_between(x+7,0,mlab.normpdf(x, mu, sigma), color='red',alpha=0.5,label="PEAK4", interpolate=True) 
axis[1].fill_between(x+6.5,0,mlab.normpdf(x, mu, sigma), color='yellow',alpha=0.5,label="PEAK5", interpolate=True) 
axis[1].plot(x2,2.5*mlab.normpdf(x2, mu2, sigma2),color='black',linestyle="",label="Exp", marker="o", markersize=4) 

axis[2].fill_between(x+6,0,mlab.normpdf(x, mu, sigma), color='green',alpha=0.5,label="PEAK1", interpolate=True) 
axis[2].fill_between(x+4,0,mlab.normpdf(x, mu, sigma), color='orange',alpha=0.5,label="PEAK2", interpolate=True) 
axis[2].fill_between(x+3,0,mlab.normpdf(x, mu, sigma), color='#73d216',alpha=0.5,label="PEAK3", interpolate=True) 
axis[2].fill_between(x+7,0,mlab.normpdf(x, mu, sigma), color='red',alpha=0.5,label="PEAK4", interpolate=True) 
axis[2].plot(x2,2.5*mlab.normpdf(x2, mu2, sigma2),color='black',linestyle="",label="Exp", marker="o", markersize=4) 


axis[3].fill_between(x+6,0,mlab.normpdf(x, mu, sigma), color='green',alpha=0.5,label="PEAK1", interpolate=True) 
axis[3].fill_between(x+4,0,mlab.normpdf(x, mu, sigma), color='purple',alpha=0.5,label="PEAK2", interpolate=True) 
axis[3].fill_between(x+3,0,mlab.normpdf(x, mu, sigma), color='blue',alpha=0.5,label="PEAK3", interpolate=True) 
axis[3].fill_between(x+7,0,mlab.normpdf(x, mu, sigma), color='red',alpha=0.5,label="PEAK4", interpolate=True) 
axis[3].fill_between(x+6.5,0,mlab.normpdf(x, mu, sigma), color='#73d216',alpha=0.5,label="PEAK5", interpolate=True) 
axis[3].fill_between(x+5.5,0,mlab.normpdf(x, mu, sigma), color='violet',alpha=0.5,label="PEAK6", interpolate=True) 
axis[3].plot(x2,2.5*mlab.normpdf(x2, mu2, sigma2),color='black',linestyle="",label="Exp", marker="o", markersize=4) 



for i in range(nrows): 
    h, l = axis[i].get_legend_handles_labels() 
    for hi, li in zip(h,l): 
     if not is_inlist(hi, lines): 
      lines.append(hi) 
      labels.append(li) 






# only 3 Legend entrys Label1 , Label2 and Label3 are visible .. Differences in cloors and markers are ignored 
plt.legend(handles=lines, labels=labels,bbox_to_anchor=(0., nrows-1+.02, 1., .102), loc=3,ncol=3, prop=legend_properties,mode="expand", borderaxespad=0.,frameon=False,framealpha=0.0) 


plt.show() 

:ImportanceOfBeingErnestの説明に基づいて

ソリューションは、関連記事Link7に与えました比較が必要なオブジェクト

+0

なしはあなたのために働いていますか?私は単純な 'ax.legend(bbox_to_anchor =(1.05,0)、loc = 'lower center'、borderaxespad = 0)を提案します。' –

+0

あなたはコードを手動で入力する必要があります。コード。 – ngoldbaum

+0

もし私があなたが私が得ることを行う場合:AttributeError: 'numpy.ndarray'オブジェクトに属性 '凡例'がありません!上記の質問を追加しました。 – NorrinRadd

答えて

1

Edit2は有望です。次に、ラベルがすでにラベルリストに入っているかどうかを確認し、そうでなければ追加します。もちろん私は以下のことをテストすることはできませんが、少なくともコンセプトを示すべきです。

lines=[] 
labels=[] 
for idata, datafile in enumerate(datafiles): 

    MYData = The_predefined_plotting_class.from_file(datafile) 

    axis[idata] = The_predefined_plotting_class.get_plot(*kwargs) 
    h, l = axis[idata].get_legend_handles_labels() 

    for handle, label in zip(h, l): 
     if label not in labels: 
      lines.append(handle) 
      labels.append(label) 

plt.legend(handles=lines, labels=labels, loc="upper left", bbox_to_anchor=[0, 1],ncol=3, shadow=True, title="Legend", fancybox=True) 
plt.show() 

あなたはdiplicateハンドルをaviodしたい場合は、それらが同じ表示され、類似したアーティストは、すでにハンドルリストに存在するかどうかを確認する特性を使用することができます。リンクの質問でのソリューションの

def is_inlist(handle, handles): 
    for h in handles: 
     if h.get_color() == handle.get_color() and \ 
      h.get_linestyle() == handle.get_linestyle() and \ 
      h.get_marker() == handle.get_marker(): 
      return True 
    return False 

lines=[] 
labels=[] 
for i in range(nrows): 
    h, l = axis[i].get_legend_handles_labels() 
    for hi, li in zip(h,l): 
     if not is_inlist(hi, lines): 
      lines.append(hi) 
      labels.append(li) 

plt.legend(handles=lines, labels=labels) 

enter image description here

+0

@NorrinRadd次回は[mcve]を提供してください。そうでなければ、何か助けを与えることは本当に難しいです。 – ImportanceOfBeingErnest

+0

早くに...もし2つのラベルにハンドルが「接続」されていれば、上記の解決策はそれを削除します。つまり、サブプロットには要素aがあり、要素cには赤があり、cublotには要素aがあります唯一の緑は、凡例に表示されます。しかし、これは当てはまりません。あなたは何か考えていますか? – NorrinRadd

+0

ハンドルは2つのラベルにどのように接続できますか?いずれにせよ、私がすでに言ったように、あなたに良い解決策を提供するには、[mcve]が必要です。そのような例のために 'The_predefined_plotting_class'などが必要ないことを覚えておいてください。問題を示す作業コードが必要です。問題が解決した場合は、問題を解決することができます。 – ImportanceOfBeingErnest

関連する問題