【问题标题】:legend() not displaying datasets properlylegend() 没有正确显示数据集
【发布时间】:2023-03-18 21:00:02
【问题描述】:

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

问题是 legend() 倾向于显示 4 个项目:红色方块、红色方块、蓝色圆圈、蓝色 cricle,而我只需要其中两个,即红色方块代表 Type2,蓝色圆圈代表 Type1。

Type2  Mean2    SD2
A      4.1     1.9
A      5.7     0.9
A      7.5     1.2
B      6.9     0.7
B      4.9     0.4
B      8.5     1

Type1 Mean1    SD1
A      8.1      1
A      7.7     0.9
A      8.5     1.1
B      5.9     0.4
B      7.9     0.7
B      9.5     1.2

Figure1 = plt.figure('Scatter Plot', figsize=(6,6), dpi=300)
Subplot1 = Figure1.add_subplot(1,1,1)

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['Mean2'],)))
    Subplot1.errorbar(x, y= Mean2 , yerr= SD2 ,
                      fmt=m,
                      markersize=5, color=c,
                      capsize=3, markeredgewidth=0.5
                      )

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

Subplot1.set_xlim(-0.5,1.5)

###############################################
###############################################

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['Mean1'],)))
    Subplot1.errorbar(x, y= Mean1, yerr= SD1,
                      fmt=m,
                      markersize=5, color=c,
                      capsize=3, markeredgewidth=0.5
                      )

###############################################
###############################################
Subplot1.legend(['Type2','not needed!', 'Type1','not needed!'])

任何 cmets 都将受到高度赞赏。非常感谢!

【问题讨论】:

  • 您的代码无法重现。例如d['Mean1'] 未知。

标签: python matplotlib


【解决方案1】:

Matplotlib 只会将带有 label 的项目添加到图例中。您可以对errorbar 的标签分配使用三元运算,只为每个 groubby 对象的第一次迭代提供标签。

例子:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df1 = pd.DataFrame({'Type1': ['A', 'A', 'A', 'B', 'B', 'B'],
                    'y_mean1': [8.1, 7.7, 8.5, 5.9, 7.9, 9.5],
                    'y_SD1': [1.0, 0.9, 1.1, 0.4, 0.7, 1.2]})
df2 = pd.DataFrame({'Type2': ['A', 'A', 'A', 'B', 'B', 'B'],
                    'y_mean2': [4.1, 5.7, 7.5, 6.9, 4.9, 8.5],
                    'y_SD2': [1.9, 0.9, 1.2, 0.7, 0.4, 1.0]})
df1['x'] = np.random.rand(6)
df2['x'] = np.random.rand(6)

fix, ax = plt.subplots(1,1)

for i, (glab, g) in enumerate(df1.groupby('Type1')):
    h1 = ax.errorbar(g.x,
                     g.y_mean1,
                     g.y_SD1,
                     fmt='o',
                     c='b',
                     capsize=3,
                     markeredgewidth=0.4,
                     elinewidth=0.4,
                     # label is only assigned on the first iteration
                     label='Type1' if not i else None)
for i, (glab, g) in enumerate(df2.groupby('Type2')):
    h2 = ax.errorbar(g.x,
                     g.y_mean2,
                     g.y_SD2,
                     fmt='s',
                     c='r',
                     capsize=3,
                     markeredgewidth=0.4,
                     elinewidth=0.4,
                     # label is only assigned on the first iteration
                     label='Type2' if not i else None)
ax.legend()

【讨论】:

  • 谢谢。您的情节看起来不像原来的情节,因为它摆脱了子组 A 和 B。如果您可以调整原始代码以说明您添加的新代码行,即 label='Type1' if not i else没有任何。我继续添加了这行代码,但它似乎没有以正确的方式工作。添加此行不会改变任何内容。
  • 我无法调整您的原始代码,因为它包含对您尚未定义的对象的引用。
  • 你能不能更精确一点。这里有什么未定义的?您的回答不适用于我的情况。
  • 在x = np.random.normal(loc=i,scale=0.2,size=(len(d['Mean2'],))) 中,变量d 未定义。在Subplot1.errorbar(x, y= Mean1, yerr= SD1, ... 中,Mean1 和 SD1 均未在您提供的代码中定义。
  • Mean1 和 Mean2 只是每组数据的 y 轴值(您可以在代码顶部查看数据)。还为这一行中的每个数据集定义了dfor i,((g,d),m,c) in enumerate(zip(grouped,markers,colors)):
猜你喜欢
  • 2020-01-19
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多