How to plot two variables on two different y-axes in python? [duplicate]

I try to build a graphy with one x-axis and two y-axes, with all axes comming from a dataframe (similar to the graphs here). Here are my example data:

import pandas as pd df = pd.DataFrame(data={'year': [2000, 2001, 2002], 'deaths': [327, 456, 509], 'cheese': [13.5, 13.7, 13.8]}) 

I only found questions covering multiple lines based on a categorical variable (what I don't need) or more than two axis with an answer I, as a beginner, don't understand.

0

1 Answer

The matplotlib.pyplot module creates a figure and axes object (see help(plt.subplots) for details) that can be used to create a plot as requested:

import matplotlib.pyplot as plt # Impot the relevant module fig, ax = plt.subplots() # Create the figure and axes object # Plot the first x and y axes: df.plot(x = 'year', y = 'deaths', ax = ax) # Plot the second x and y axes. By secondary_y = True a second y-axis is requested: # (see for details) df.plot(x = 'year', y = 'cheese', ax = ax, secondary_y = True) 

Output:

Output

2

You Might Also Like