How can I make a figure with 2 charts, and both charts have dual Y axis in matplotlib?

You can use the matplotlib.pyplot
library to create a figure with two charts and dual Y axes. Here's an example of how you can do this:
import matplotlib.pyplot as plt
# Create figure and axes
fig, ax1 = plt.subplots()
# Create second Y axis
ax2 = ax1.twinx()
# Plot data on first Y axis
ax1.plot(data1, '-b', label='Data 1')
# Plot data on second Y axis
ax2.plot(data2, '-r', label='Data 2')
# Set labels and limits for first Y axis
ax1.set_ylabel('Data 1', color='b')
ax1.set_ylim(0, 10)
# Set labels and limits for second Y axis
ax2.set_ylabel('Data 2', color='r')
ax2.set_ylim(0, 100)
# Add legend
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
# Show plot
plt.show()
In this example, we first create a figure
object and axes
object using plt.subplots()
. Then we create a second Y axis object ax2
by calling the twinx()
method on the first axis object ax1
. This will create a new axis object that shares the same x-axis as the first axis but has its own y-axis.
Next, we plot the data on the two Y axis using the plot()
method. We then set the labels and limits for each axis using the set_ylabel()
and set_ylim()
methods.
Finally, we add a legend to the plot using the legend()
method. We can specify the location of the legend using the loc
parameter. plt.show()
is used to display the figure.
This should produce a figure with two charts, each with its own Y axis, and a common X axis.
You can also make use of make_axes_locatable
function to create twin x-axis and twin y-axis for your plots.