Skip to content

Support for legend with "handles" and "labels" like MATLAB/matplotlib #260

@liamtoney

Description

@liamtoney

Description of the desired feature

A wrapper for the GMT 6 legend command with support for specifying "handles" and "labels" as arguments, as in MATLAB (legend docs) and matplotlib (legend docs). The plotting commands (i.e., gmt.Figure.plot(), for now) are modified to return "handles" which are provided as inputs to gmt.Figure.legend(). This addresses part of #214 and #231.

Below is a minimal working example using my add-legend fork:

import gmt

fig = gmt.Figure()

h1 = fig.plot(x=[-5], y=[5], region=[-10, 10, -5, 10], projection='X3i/0', frame='a',
              style='a15p', pen='1.5p,purple')

h2 = fig.plot(x=[0], y=[5],
              style='t10p', color='cyan')

h3 = fig.plot(x=[5], y=[5],
              style='d5p', color='yellow', pen=True)

fig.legend([[h1, h2, h3], ['I am a star!', 'I am a triangle!', 'I am a diamond!']],
           F=True, D='g0/0+w2i+jCM')    

fig.show()

example

Are you willing to help implement and maintain this feature?

Yes. You can view the source code for my implementation here.

The good news:

  • The legend wrapper accepts either the standard specfile (see GMT legend docs) or a list containing a list of handles and a list of labels. So folks can still build a complex legend by creating a specfile.
  • The only modification to gmt.Figure.plot() is that it now returns kwargs. So existing users won't have to change their syntax for the plot command.

The bad news:

  • This implementation makes use of GMTTempFile since I don't know how to do it any other way (yet).
  • Right now I'm using regular expression matching (via re) to separate symbol type and size from the style argument of gmt.Figure.plot(), which is probably really sketchy.
  • This only works for symbol entries in the legend, i.e. entries in specfile which have the form:
    S - symbol size fill pen - text
    I feel like this covers a broad portion of typical legend use cases, though.
  • I have not written any tests.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions