2017-07-06 18 views
1

我阅读了以前的解决方案,但无法使其中任何一个工作。我想为每个子图都有一个全球图例。 此副区的斧目的是通过预定义的函数“get_plot”产生了一个预定义的类 “The_predefined_plotting_class”大致是这样的:具有不同内容的子图的全球图例

My code

该函数返回斧头对象和每斧对象具有多个从原始“数据文件”的多列中“绘制”/绘图。

在我在这个网站上找到的解决方案之一,我读,我可以用:

enter image description here

,使全球的传奇。不幸的是,我不知道如何追加单个的ax对象(或其中的数据)来处理这个工作。 每个地块包含一些相同的列名称和一些不同。如果一个条目/名称存在于许多子图中,则只应打印一次。

Solution1

Solution2

Solution3

编辑

,我真的很抱歉,我不得不使用图片,但无论我做了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

这是部分形成在产生实际的地块有问题的脚本。 “列”只包含要绘制的实际数据的名称。

# 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 

EDIT6

我想基于这样的想法我这里介绍找到一个解决办法:

Iteration though lists

不幸的是什么工作了包含字符串为不起作用两个列表看起来好像是艺术家。

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() 

我认为问题是,只对内存ADRESS字符串中

if hl not in LI: 

不是“H”的实际内容进行比较?基于ImportanceOfBeingErnest的解释

解决在相关的帖子Link7了:

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() 

这里我的真实数据反映更好,因为我有两个matplotlib.collections.PolyCollection)和matplotlib.lines.Line2D这些对象需要进行比较。

+0

在问题解决方案中没有链接这个工作了吗?我建议一个简单的'ax.legend(bbox_to_anchor =(1.05,0),loc ='lower center',borderaxespad = 0。)' –

+0

你需要手动输入代码,不知何故,你粘贴的截图代码。 – ngoldbaum

+0

如果我按照你的建议得到:AttributeError:'numpy.ndarray'对象没有属性'legend'!我在上面添加了一个问题。 – 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() 

如果你想aviod diplicate手柄,你可以使用,使它们看起来相等,并查看是否有类似的艺术家已经存在于手柄列表中的属性。

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

要早...如果一个句柄“连接”到两个标签上面的解决方案删除它反正....这意味着如果一个子图具有和元素a是colord红色,另一个cublot具有一个元素a是彩色的绿色只有第一个出现在传说中。但事实并非如此。你有什么主意吗? – NorrinRadd

+0

手柄如何连接到两个标签?无论如何,正如我已经说过的,[mcve]是必要的,能够为您提供一个好的解决方案。请注意,对于这样的示例,您不需要'The_predefined_plotting_class'左右。您只需要显示问题的工作代码,并且如果更正,就可以解决您的问题。 – ImportanceOfBeingErnest

相关问题