0

When I plot two columns of my dataframe, where one contains the x-values and the other one the y-values, I do not manage to show a legend. This is because there are non handles in the legend call. But I did not figure out how to create those handles out of the dataframe.

plt.figure(num=None, figsize=(15, 6), dpi=80, facecolor='w', edgecolor='k')
colordict = {'m':'blue', 'f':'red'}

plt.scatter(x=df.p_age, y=df.p_weight, c=df.p_gender.apply(lambda x: colordict[x]))
plt.title('Weight distribution per age')
plt.xlabel('Age [months]')
plt.ylabel('individual weight [kg]')
plt.legend(title="Legend Title")

The color-dictionnary colordict is so I can have different colors for the two genders. That works. And I want a legend with a blue and a red dot and "male", "female" next to it. I have tried:

plt.legend(title="Legend Title", handles=(df.p_age,df.p_weight))

But that does not work, as handles cannot be made out of series.

Aneho
  • 118
  • 7

1 Answers1

0

Derived from the solution found here. This solution iteratively draws the plot for each class.

fig, ax = plt.subplots()

for gender,color in colordict.items():
    scatter = ax.scatter(x=df.p_age, y=df.p_weight, c=color,label=gender)

ax.legend()
plt.show()
Manik Tharaka
  • 298
  • 3
  • 9