mofs
mofs

Reputation: 113

Matplotlib scatter plot legend, as separate image

I am using ax.scatter(x,y,c=color, s=size, marker='*', label="mylabel") to plot 4 symbols in a scatter plot (markers are ',', 'o','*', and '^') each with differing sizes and colors.

I have tried calling ax.legend() and, although I get the expected label information, none of the markers appear in the legend. I attempted using a number of variations explained here with no avail: http://matplotlib.org/users/legend_guide.html

Furthermore, I ultimately need my legend to be in a completely separate image. I have tried: Get legend as a separate picture in Matplotlib

and

https://pymorton.wordpress.com/2016/04/05/creating-separate-legend-figure-with-matplotlib/

but haven't been able to display the markers. Any advice would be appreciated!

Here is my plotting code:

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
from scipy import stats

lat = np.random.randint(-60.5, high=60.5, size=257087)
lon = np.random.randint(-179.95, high=180, size=257087)
thiscategory =  np.random.randint(12, 60, size=257087)

percRange = np.arange(100,40,-1)


#Rank all values
allPercent=stats.rankdata(thiscategory)/len(thiscategory)

h=np.where(allPercent > 0.9)
hl=np.where((allPercent <= 0.9) & (allPercent > 0.8))
mh=np.where((allPercent <= 0.8) & (allPercent > 0.7))
ml=np.where((allPercent <= 0.7) & (allPercent > 0.6))
l=np.where(allPercent <= 0.6)

allPercent[h]=0
allPercent[hl]=0.25
allPercent[mh]=0.5
allPercent[ml]=0.75
allPercent[l]=1


fig = plt.figure(dpi=400)
ax=fig.add_axes([0,0,1,1]) #position: left, bottom, width, height
ax.set_axis_off()
fig.patch.set_facecolor('none')

latcorners = ([-90.0,90.0])
loncorners = ([-180.0,180.0])


rgba_low=colors.hex2color('#e0ffff') #224-255-255 Light Cyan
rgba_ml=colors.hex2color('#afeeee') #175-238-238 Pale Turquoise
rgba_mh=colors.hex2color('#ffff00') #Yellow 
rgba_hl=colors.hex2color('#ffa500')  #Orange
rgba_high=colors.hex2color('#f8f8ff') #ghost white

m = Basemap(projection='cyl',llcrnrlat=latcorners[0],urcrnrlat=latcorners[1],llcrnrlon=loncorners[0],urcrnrlon=loncorners[1])                       
# Draw on map.
x, y = m(lon, lat)



ax.scatter(x[ml],y[ml], c=rgba_ml, s=3, marker=',',edgecolor='none', alpha=0.4, label=str(mlmin)+" to "+str(mlmax))
ax.scatter(x[mh],y[mh], c=rgba_mh, s=5, marker='o', edgecolor='none', alpha=0.5, label=str(mhmin)+" to "+str(mhmax))
ax.scatter(x[hl],y[hl], c=rgba_hl, s=10, marker='*',edgecolor='none', alpha=0.6, label=str(hlmin)+" to "+str(hlmax))
ax.scatter(x[h],y[h], c=rgba_high, s=20, marker='^', edgecolor='none',alpha=0.7, label=str(hmin)+" to "+str(hmax))

ax.set_xlim([-180,180])
ax.set_ylim([-90,90])

#this is where my legend calls were going, but since I want them in a new plot it doesn't seem appropriate


fig.savefig('testfig.jpg', bbox_inches='tight', transparent=True, pad_inches=0)

*edited to show sample code.

Upvotes: 0

Views: 2460

Answers (1)

mofs
mofs

Reputation: 113

Here is what i found: I had to modify the code I found to not include a figure call. After plotting the scatter (ax.scatter) I called:

handles,labels = ax.get_legend_handles_labels()

After plotting the main plot and closing the figure I called a new figure:

fig_legend = plt.figure(figsize=(2,2))
axi = fig_legend.add_subplot(111)            
fig_legend.legend(handles, labels, loc='center', scatterpoints = 1)
axi.xaxis.set_visible(False)
axi.yaxis.set_visible(False)
fig_legend.canvas.draw()
fig_legend.show()

The final results contains two black borders, but it is a separate image and has a single instance of the scatter symbol in the correct color.legend image example here

Upvotes: 6

Related Questions