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

时间:2019-04-25 11:11:41

标签: python pandas matplotlib plot axis

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

import pandas as pd

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

我只发现了涉及multiple lines based on a categorical variable (what I don't need)more than two axis with an answer I, as a beginner, don't understand的问题。

1 个答案:

答案 0 :(得分:0)

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) 

输出:

Output