Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/111.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 控件Legend()以显示特定的数据集_Python_Dataframe_Matplotlib_Plot_Legend - Fatal编程技术网

Python 控件Legend()以显示特定的数据集

Python 控件Legend()以显示特定的数据集,python,dataframe,matplotlib,plot,legend,Python,Dataframe,Matplotlib,Plot,Legend,我试图在图例中显示两个主要数据集,即“Type2”(红色方块)和“Type1”(蓝色圆圈)。尽管如此,由于我的绘图涉及“类型1”和“类型2”的子组(A、B分别为每个子组),图例中出现了4个项目。请看一下仅使用“类型”时我的绘图的外观: 问题是legend()倾向于显示4项:红方块、红方块、蓝圈、蓝圈,而我只需要其中两项,即红方块表示Type1,线索圈表示Type2 Figure1 = plt.figure('Scatter Plot') Subplot1 = Figure1.add_subpl

我试图在图例中显示两个主要数据集,即“Type2”(红色方块)和“Type1”(蓝色圆圈)。尽管如此,由于我的绘图涉及“类型1”和“类型2”的子组(A、B分别为每个子组),图例中出现了4个项目。请看一下仅使用“类型”时我的绘图的外观:

问题是legend()倾向于显示4项:红方块、红方块、蓝圈、蓝圈,而我只需要其中两项,即红方块表示Type1,线索圈表示Type2

Figure1 = plt.figure('Scatter Plot')
Subplot1 = Figure1.add_subplot(1,1,1)

########## PLOT Type2 Data ##################
markers = ['s','s']
colors = ['r', 'r']
grouped = DataFrame.groupby('Type2')

for i,((g,d),m,c) in enumerate(zip(grouped,markers,colors)):
    x = np.random.normal(loc=i,scale=0.2,size=(len(d['Y2'],))) 
    G_object1, _ = Subplot1.errorbar(x, y=d['Y2'], yerr=d['SD2'], 
                  fmt=m, color=c, capsize=3)

XPos = list(range(len(grouped)))
Subplot1.set_xticks(XPos)
Subplot1.set_xticklabels([a for a in grouped.groups])

########## PLOT Type1 Data ##################
markers = ['o','o']
colors = ['b', 'b']
grouped = DataFrame.groupby('Type1')

for i,((g,d),m,c) in enumerate(zip(grouped,markers,colors)):
    x = np.random.normal(loc=i,scale=0.2,size=(len(d['Y1'],))) 
    G_object2,_ = Subplot1.errorbar(x, y=d['Y1'], yerr=d['SD1'], 
                  fmt=m, color=c, capsize=3)

Subplot1.legend(['Type1','Type2'], [G_object1,G_object2])

如有任何意见,我们将不胜感激。非常感谢。

从轴访问图形对象,然后将它们传递到图例中:

# do this separately for each graph
ax.errorbar(x,d['Y1'],yerr=d['Err1'], fmt=m, color=c, capsize=3)
ax.errorbar(x,d['Y2'],yerr=d['Err2'], fmt=m, color=c, capsize=3)

# pass line objects into a legend
ax.legend([x for x in ax.lines],['Type1','Type2'], fontsize=15, title_fontsize = 16, loc='upper left', shadow=True)

如果问题与matplotlib有关,您应该向其添加标记。我现在更新了上面的原始代码,以包含您所注意到的内容。但是我得到了一个错误:“ValueError:太多的值无法解包(预期为2)”。你能再快速看一下代码吗?非常感谢。@Riccardo。您不应该更改问题中的原始代码,因为这会使答案无效。您可以添加编辑,或者如果需要其他帮助,可以添加另一个问题。看起来我的订单错了。首先绘制对象,然后绘制线。更正@RiccardoUpdated,使其更容易一些它仍然没有正确显示图例。我得到的是Type1的一个红方块(即使只是简单地做:ax.legend(['Type1','Type2'])和Type2的一个“虚线”。事实上,我希望Type2能得到一个“蓝色圆圈”,而不是一个“破折号”。有什么建议吗?谢谢@YaakovBressler