Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 851
Qaswed Avatar asked Apr 25 '19 11:04

Qaswed


People also ask

How do I make multiple Y-axis in matplotlib?

Create multiple y axes with a shared x axis. This is done by creating a twinx axes, turning all spines but the right one invisible and offset its position using set_position .


1 Answers

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 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html for details)
df.plot(x = 'year', y = 'cheese', ax = ax, secondary_y = True) 

Output:

Output

like image 136
Qaswed Avatar answered Nov 13 '22 16:11

Qaswed