Make custom legend with Julia Pyplot

Viewed 749

I would like to make a custom legend in Julia's pyplot, in which the legend labels are not necessarily related to individual series plotted on the graph. For example:

enter image description here

In Python (pyplot comes from matplotlib) this could be done with:

from matplotlib.lines import Line2D
custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
                Line2D([0], [0], color=cmap(.5), lw=4),
                Line2D([0], [0], color=cmap(1.), lw=4)]

fig, ax = plt.subplots()
lines = ax.plot(data)
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot'])

The issue is I cannot seem to access the Line2D object in pyplot (using pyplot as plt, plt.lines.Line2D does not work).

Any workaround?

2 Answers

I know it is not pyplot but MakieLayout will solve your problem:

enter image description here

Link to the example with code.

I got the answer from Julia Discourse.

I wasn't satisfied with the existing answer, but I managed to figure it out. Per the PyPlot.jl docs under Exported Functions,

(And the raw PyObject for the matplotlib modules is also accessible as PyPlot.matplotlib.)

So you can achieve your goal by just putting the full call in (I assign to a variable to avoid making the custom_lines ugly):

L2D = PyPlot.matplotlib.lines.Line2D
custom_lines = [L2D([0], [0], color=cmap(0.), lw=4),
                L2D([0], [0], color=cmap(.5), lw=4),
                L2D([0], [0], color=cmap(1.), lw=4)]

fig, ax = plt.subplots()
lines = ax.plot(data)
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot'])
Related