# matplotlib twinx legend

I have a plot with two y-axes, using twinx(). In this example, we will plot a sine curve and a hyperbolic sine curve in the same plot with a common x-axis having different y-axis. You can easily add a second legend by adding the line: But if you want all labels on one legend then you should do something like this: I'm not sure if this functionality is new, but you can also use the get_legend_handles_labels() method rather than keeping track of lines and labels yourself: From matplotlib version 2.1 onwards, you may use a figure legend. I also give labels to the lines, and want to show them with legend(), but I only succeed to get the labels of one axis in the legend: import numpy as np import matplotlib.pyplot as plt from matplotlib import rc rc('mathtext', defa ax2 = ax1.twinx() Axes.twinx() creates a new Axes with a y-axis that is opposite to the original axis, in this example ax1. In this article we will show you some examples of legends using matplotlib. The former may be the coordinates of the edge defined by loc given in axes coordinates.
Related course.

One of the options is to make a single plot with two different y-axis, such that the y-axis on the left is for one variable and the … Au lieu de ax.legend(), qui produit une légende avec les poignées des axes ax, on peut créer une légende de figure . Instead of ax.legend(), which produces a legend with the handles from the axes ax, one can create a figure legend. In this article we will show you some examples of legends using matplotlib. How to Automate Plot Updates in Matplotlib, How to Plot Data in Real Time Using Matplotlib, How to Change Figure Size and Its Format in Matplotlib, How to Manually Set the Size of the Bins in Matplotlib Histogram, How to Add a Y-Axis Label to the Secondary Y-Axis in Matplotlib, How to Plot Logarithmic Axes in Matplotlib, How to Add Title to Subplots in Matplotlib, How to Connect Scatterplot Points With Line in Matplotlib.
The latter would be the axes transform of the axes the legend should reside in. I also give labels to the lines, and want to show them with legend(), but I only succeed to get the labels of one axis in the legend: So I only get the labels of the first axis in the legend, and not the label 'temp' of the second axis. fig.legend(loc="upper right") which will gather all handles from all subplots in the figure. Legends can be placed in various positions: A legend can be placed inside or outside the chart and the position can be moved. I found an following official matplotlib example that uses host_subplot to display multiple y-axes and all the different labels in one legend. which will gather all handles from all subplots in the figure. You can easily get what you want by adding the line in ax: This would plot nothing but add a label to legend of ax. Matplotlib has native support for legends.