Sort legend

Hi everybody, I have posted this question already on stackoverflow but I figured this might be the better place to ask:

I want to create a map with pygmt, where I show the tracks of 4 cruises. They do partially overlap and one cruise is of special interest to me, hence I like to have it on top. The legend, however, should be sorted by date but the desired cruise was not the most recent one. Is there a way in pygmt to reorder the legend entries (as one can do for example by means of matplotlib.axes.Axes.get_legend_handles_labels)? Another possible option that came to my mind was the usage of something like the zorder option in matplotlib.pyplot.plot but I’m not aware of something similar in pygmt.

I hope this suffices as example code:

region,frame="g","g"
projection = 'G20.5/89.99999/25/4.5i' # yeah that’s the arctic…
fig = pygmt.Figure()
fig.coast(projection=projection, region=region, frame=frame, W=True) # plot cost lines
pen=0.9
fig.plot(cruise1_lon, cruise1_lat,label='"Cruise 1"',pen=('black',pen))
fig.plot(cruise2_lon, cruise2_lat,label='"Cruise 2"',pen=('green',pen))
fig.plot(cruise4_lon, cruise4_lat,label='"Cruise 4"',pen=('purple',pen)) # most recent one
fig.plot(cruise3_lon, cruise3_lat,label='"Cruise 3"',pen=('yellow',pen)) # should be plotted above the other cruises
fig.legend(position='JTL+jTL+o0.2c',box='+gwhite+p1p') 
# should be sorted as: Cruise 1, Cruise 2, Cruise 3, Cruise 4, 
# but is sorted as: Cruise 1, Cruise 2, Cruise 4, Cruise 3
fig.show()

Has anybody any idea how I could archive that, without having to somehow manually create the legend?

Thanks in advance!

I do not use pygmt. But I think that maybe a workaround would be to plot the cruises in the order that you want to plot in the legend. And then add an extra line so the cruise that you want (3?) appears on top.

fig.plot(cruise1_lon, cruise1_lat,label='"Cruise 1"',pen=('black',pen))
fig.plot(cruise2_lon, cruise2_lat,label='"Cruise 2"',pen=('green',pen))
fig.plot(cruise3_lon, cruise3_lat,label='"Cruise 3"',pen=('yellow',pen))
fig.plot(cruise4_lon, cruise4_lat,label='"Cruise 4"',pen=('purple',pen)) # most recent one

fig.plot(cruise3_lon, cruise3_lat,',pen=('yellow',pen))  # plot cruise 3 again but without label.

Ohh, right. Such a simple solution, at least as workaround. Thanks!

1 Like