创建具有两个y轴的Matplotlib图的最简单方法是使用twinx()函数。
下面的例子展示了如何在实践中使用这个函数。
例子。创建具有两个Y轴的Matplotlib绘图
假设我们有以下两个pandas DataFrames。
import pandas as pd
#create DataFrames
df1 = pd.DataFrame({'year': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'sales': [14, 16, 19, 22, 24, 25, 24, 24, 27, 30]})
df2 = pd.DataFrame({'year': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'leads': [4, 4, 4, 5, 4, 5, 7, 8, 5, 3]})
两个DataFrame都共享'year'变量,其范围从1到10,但是第一个DataFrame显示的是每年的总销售额,而第二个DataFrame显示的是每年的总线索。
我们可以使用下面的代码来创建一个Matplotlib图表,在一个有两个Y轴的图表上显示销售额和销售线索。
import matplotlib.pyplot as plt
#define colors to use
col1 = 'steelblue'
col2 = 'red'
#define subplots
fig,ax = plt.subplots()
#add first line to plot
ax.plot(df1.year, df1.sales, color=col1)
#add x-axis label
ax.set_xlabel('Year', fontsize=14)
#add y-axis label
ax.set_ylabel('Sales', color=col1, fontsize=16)
#define second y-axis that shares x-axis with current plot
ax2 = ax.twinx()
#add second line to plot
ax2.plot(df2.year, df2.leads, color=col2)
#add second y-axis label
ax2.set_ylabel('Leads', color=col2, fontsize=16)
图中左侧的Y轴显示了每年的总销售额,右侧的Y轴显示了每年的总线索。
图中的蓝线代表每年的总销售额,红线代表每年的总线索。
请随意使用标记和线宽参数来改变图表中线条的外观。
import matplotlib.pyplot as plt
#define colors to use
col1 = 'steelblue'
col2 = 'red'
#define subplots
fig,ax = plt.subplots()
#add first line to plot
ax.plot(df1.year, df1.sales, color=col1, marker='o', linewidth=3)
#add x-axis label
ax.set_xlabel('Year', fontsize=14)
#add y-axis label
ax.set_ylabel('Sales', color=col1, fontsize=16)
#define second y-axis that shares x-axis with current plot
ax2 = ax.twinx()
#add second line to plot
ax2.plot(df2.year, df2.leads, color=col2, marker='o', linewidth=3)
#add second y-axis label
ax2.set_ylabel('Leads', color=col2, fontsize=16)

请注意,这两条线现在都更宽了,并且包含 "o "标记,以显示单个数据点。
其他资源
下面的教程解释了如何在Matplotlib中执行其他常见的操作。
如何在Matplotlib中调整轴标签位置
如何在Matplotlib中设置轴的范围
如何在Matplotlib中设置X轴值
The postHow to Create a Matplotlib Plot with Two Y Axesappeared first onStatology.