Python双Y轴绘图:以Distance为X轴关联Height与Wind Speed
双Y轴可视化Distance与Height、Wind Speed的关联
需求说明
现有如下结构的DataFrame:
| Distance | Height | Wind Speed |
|---|---|---|
| 0.25 | 10 | 5.2 |
| 0.56 | 15 | 3.2 |
| ........ | ....... | ........... |
其中Distance是Height和Wind Speed的函数,需要绘制以Distance为X轴,同时将Height和Wind Speed作为两个独立Y轴的散点/折线图,体现三者的关联关系。此前单Y轴绘制两条曲线的方式无法清晰区分两个变量的数值尺度,也难以直观展示同一Distance下两者的对应关系。
实现方法
可以通过Matplotlib的twinx()方法创建共享X轴的第二个Y轴,以此实现双Y轴可视化,具体代码如下:
import matplotlib.pyplot as plt import pandas as pd # 假设df是你的目标DataFrame fig, ax1 = plt.subplots(figsize=(10, 6)) # 第一个Y轴:Height与Distance的关系 color = 'tab:blue' ax1.set_xlabel('Distance') ax1.set_ylabel('Height', color=color) # 折线图,若需要散点图可将plot改为scatter ax1.plot(df['Distance'], df['Height'], marker='o', color=color, label='Height') ax1.tick_params(axis='y', labelcolor=color) # 创建共享X轴的第二个Y轴:Wind Speed与Distance的关系 ax2 = ax1.twinx() color = 'tab:red' ax2.set_ylabel('Wind Speed', color=color) ax2.plot(df['Distance'], df['Wind Speed'], marker='s', color=color, label='Wind Speed') ax2.tick_params(axis='y', labelcolor=color) # 合并两个轴的图例 lines1, labels1 = ax1.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right') plt.title('Distance vs Height & Wind Speed') plt.show()
效果说明
- 两个Y轴分别匹配Height和Wind Speed的数值尺度,避免因量级差异导致某条曲线被压缩
- 每个Distance点同时对应一组Height和Wind Speed数值,能直观展示三者的关联趋势:比如Distance增大时,两个变量是同步变化还是反向变化
- 若需要散点图,只需将代码中的
plot方法替换为scatter即可
内容的提问来源于stack exchange,提问作者matrix_season
相关产品推荐
相关产品推荐

