For one project, I had to separate the legends from the plots. Doing such a thing can be tricky with the Matplotlib library or Seaborn. In this post, I will show how you can achieve the results in the cover image.
Just use this function:
|
|
It takes the handles and labels Matplotlib objects of the plot. Then it inserts them in a standalone figure. Once that’s done, crop the white spaces.
Example time
Let’s test this function in a well-known dataset. The content of this article can be applied to plots created through Matplotlib, I just used a Pandas DataFrame to build a quick example.
We load it this way:
|
|
You can apply this two ways.
For a figure with multiple curves in a single axes
To obtain a result like so:
We use this piece of code
|
|
As you can see, we need to hide the legend in the axes where you plot the data with “ax.legend().set_visible(False)”. The legend is saved separately in the file iris_legends.pdf.
For a figure with subplots
In case you want to plot every field of the dataset in different axis, do as follow:
|
|
The two results are:
Hope you find it helpful.