Home > Net >  Wrong legend in a multilines plot
Wrong legend in a multilines plot

Time:11-09

I would like to create a plot with multiple lines and legend associated with values within one specific column. The dataset is

index   Name    Frequency   Position
    0   User1   1   1
    1   User1   5   2
    2   User1   10  3
    3   User1   27  4
    4   User1   70  5
    5   User1   200 6
    6   User3   1   1
    7   User3   5   2
    8   User3   3   3
    9   User4   1   1

The code

fig, ax = plt.subplots(figsize=(10,8))
df.groupby('Name').plot(kind='line', x = "Position", y = "Frequency", ax=ax)
plt.legend()
plt.show()

correctly creates a multilines plot but the legend is wrong! In fact, Frequency is assigned to the legend. Can someone explain me where I am making the mistake?

CodePudding user response:

Since you mentioned that your multi-lines plot is fine, try this:

fig, ax = plt.subplots(figsize=(10,8))
for name, group in df.groupby('Name'):
    group.plot(x = "Position", y= "Frequency", ax=ax, label=name)
plt.show()

RESULT enter image description here

  • Related