【问题标题】:Control Legend() to display specific datasets控制 Legend() 显示特定数据集
【发布时间】:2020-01-19 23:43:53
【问题描述】:

我试图在图例中显示 2 个主要数据集,即“Type2”(红色方块)和“Type1”(蓝色圆圈)。尽管如此,由于我的情节涉及“Type1”和“Type2”的子组(A,B 是每个子组),因此图例中出现了 4 个项目。请看看我的情节如何只使用“类型”: Query on errorbar() added to stripplot

问题是 legend() 倾向于显示 4 个项目:红色方块,红色方块,蓝色圆圈,蓝色 cricle,而我只需要其中两个,即红色方块代表 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])

高度赞赏任何 cmets。非常感谢。

【问题讨论】:

  • 如果问题与 matplotlib 有关,您应该在其中添加标签。

标签: python dataframe matplotlib plot legend


【解决方案1】:

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

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

【讨论】:

  • 我现在已经更新了上面的原始代码,以包含您提到的内容。但是我收到一个错误:“ValueError:解包的值太多(预期为 2)”。你能再快速看一下代码吗?非常感谢。
  • @Riccardo。您不应更改问题中的原始代码,因为这会使答案无效。如果需要更多帮助,您可以追加编辑,或者更好的是添加另一个问题。
  • 看来我的订单有误。首先绘制对象,然后绘制线条。更正了@Riccardo
  • 已更新以使其更容易
  • 它仍然没有正确显示图例。我得到的是 Type1 的红色方块(即使只是简单地执行以下操作也是如此:ax.legend(['Type1','Type2']))和 Type2 的“虚线”。事实上,我希望为 Type2 获得一个“蓝色圆圈”,而不是一个“破折号”。对此有什么建议吗?谢谢@YaakovBressler
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多