Home > Software engineering >  Colour by Category in scatterplot
Colour by Category in scatterplot

Time:10-03

My dataframe looks like this:

date    index   count   weekday_num     max_temperature_C
0   2019-04-01  0   1379    0   18
1   2019-04-02  1   1395    1   21
2   2019-04-03  2   1155    2   19
3   2019-04-04  3   342     3   18
4   2019-04-05  4   216     4   14

I would like to plot count vs max_temperature_C and colour by weekday_num

I have tried the below:

#create the scatter plot of trips vs Temp
plt.scatter(comb2['count'], comb2['max_temperature_C'], c=comb2['weekday_num'])

# Label the axis
plt.xlabel('Daily Trip count')
plt.ylabel('Max Temp c')

plt.legend(['weekday_num'])
# Show it!
plt.show()

enter image description here

However I am not sure quite how to get the legend to display all of the colours which correspond to each of the 'weekday_num' ?

Thanks

CodePudding user response:

You can use the automated legend creation like this:

fig, ax = plt.subplots()

scatter = ax.(comb2['count'], comb2['max_temperature_C'], c=comb2['weekday_num'])

# produce a legend with the unique colors from the scatter
legend = ax.legend(*scatter.legend_elements(),
                    loc="upper right", title="Weekday num")
ax.add_artist(legend)
plt.show()
  • Related