如何在python中的两个不同y轴上绘制两个变量?

Qas*_*wed 5 python plot axis matplotlib pandas

我尝试构建一个带有一个 x 轴和两个 y 轴的图形,所有轴都来自一个数据框(类似于此处的图形)。这是我的示例数据:

import pandas as pd

df = pd.DataFrame(data={'year': [2000, 2001, 2002], 
                        'deaths': [327, 456, 509], 
                        'cheese': [13.5, 13.7, 13.8]})
Run Code Online (Sandbox Code Playgroud)

我只发现了基于分类变量(我不需要的)超过两个轴的多行问题,答案是我作为初学者不明白

Qas*_*wed 8

matplotlib.pyplot模块创建一个图形和轴对象(help(plt.subplots)有关详细信息,请参阅),可用于根据要求创建绘图:

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) 
Run Code Online (Sandbox Code Playgroud)

输出:

输出