I have created a scatter chart where I have values of a certain column ABC ranging from 0-10.
The points have 4 colours: light blue for values less than 2, blue for 2-4, orange for 4-6 and brown for 6 and above.
I have successfully generated the scatter chart, however I am finding it difficult to mention the legend on the plot.
I want a title of the legend and the legend should be in 1 row and not in multiple rows, I also want to add labels to the legend.
The variable colour_names
has the labels that I want to add to the legend.
Following is the code to create the scatter chart.
x = np.array(df['Date'])
y = np.array(df['PR'])
colours = np.array(df['colour'])
colormap = np.array(['cyan', 'dodgerblue', 'orangered','brown'])
colour_names = ['very less', 'less', 'good', 'more']
scatter = plt.scatter(x,y, c = colormap[colours], s = 5)`
I've tried the following ways to add the legend, but it neither gives an error, nor an output. The scatter gets printed properly but without the legend
`plt.legend(handles=scatter.legend_elements()[0],
labels=colour_names,
title="ABC")`
I also tried
handles = scatter.legend_elements()[0]
ax.legend(title='ABC', handles=handles, labels=colour_names)
Occasionally in my trial and error i get the following messages:-
UserWarning: Collection without array used. Make sure to specify the values to be colormapped via the c argument.
and
WARNING:matplotlib.legend:No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
You can slice the data based on your condition and plot separate scatter plots. This will work assuming your values and colors are fixed. Hope this is what you are looking for...
## My dataframe with data and PR
df=pd.DataFrame({'PR':np.random.uniform(low=0, high=4, size=(100,)),
'Date':pd.date_range('2019/07/01', periods=100, freq='SM')})
## One scatter plot each for PR value in range.. data is filtered for the range
plt.scatter(data=df[df.PR > 3], x='Date', y='PR', c = 'cyan' , s = 5, label='more')
plt.scatter(data=df[(df.PR <= 3) & (df.PR > 2)], x='Date', y='PR', c = 'dodgerblue' , s = 5, label='good')
plt.scatter(data=df[(df.PR <= 2) & (df.PR > 1)], x='Date', y='PR', c = 'orangered' , s = 5, label='less')
plt.scatter(data=df[df.PR < 1], x='Date', y='PR', c = 'brown' , s = 5, label='very less')
plt.legend(title='ABC', ncol=4)
plt.show()