Skip to content

Allow to reorder legend entries #1513

Open
@michaelgrund

Description

@michaelgrund

Description of the desired feature

In a recent Stack Overflow post the question came up if it's possible to reorder the legend entries in PyGMT (see example below, left plot). As far as I know in principle the legend entries follow the order in which the corrsponding fig.plot() calls (including the label definition) take place. However, I made a suggestion using the following workaround (right plot):

import pygmt

region,frame="g","g"
projection = 'G20.5/89.99999/25/4.5i' # yeah that’s the arctic…

# original figure
fig = pygmt.Figure()
fig.coast(projection=projection, region=region, frame=frame, shorelines=True) # plot cost lines

pen=3.9
fig.plot([90, 80, 25, 40], [90, 70, 85, 60], label='"Cruise 1"',pen=('black',pen))
fig.plot([90, 20, 10, 50], [90, 80, 80, 60], label='"Cruise 2"',pen=('green',pen))
fig.plot([90, 30, 30, 10], [90, 80, 70, 60], label='"Cruise 4"',pen=('purple',pen)) # most recent one
fig.plot([90, 80, 30, 10], [80, 80, 80, 60], 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.shift_origin(xshift="w+0.5c")

# workaround to fix the problem
fig.coast(projection=projection, region=region, frame=frame, shorelines=True)
fig.plot([90, 80, 25, 40], [90, 70, 85, 60], label='"Cruise 1"',pen=('black',pen))
fig.plot([90, 20, 10, 50], [90, 80, 80, 60], label='"Cruise 2"',pen=('green',pen))
fig.plot([90, 30, 30, 10], [90, 80, 70, 60], pen=('purple',pen)) 
fig.plot([90, 80, 30, 10], [80, 80, 80, 60], label='"Cruise 3"',pen=('yellow',pen)) 

# add dummy entry for legend entry
fig.plot([90, 90], [90, 90], label='"Cruise 4"',pen=('purple',pen)) 

fig.legend(position='JTL+jTL+o0.2c',box='+gwhite+p1p') 
fig.show()

PLOT_test

I guess it's not possible to directly implement something like the zorder option in matplotlib.pyplot.plot in PyGMT since the module is connected to GMT's plot function. However, maybe there are some ideas how we could handle that.

Are you willing to help implement and maintain this feature? First discuss

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestNew feature wantedquestionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions