如何在 Matplotlib 使用两个 Y 轴(两个单位)绘制单一数据?


要在 Matplotlib 中使用两个 Y 轴(两个单位)绘制单一数据,我们可以采取以下步骤 −

  • 设置图表大小并调整子图与周围的填充。
  • 使用 numpy 创建速度加速度数据点。
  • 将子图添加到当前图表中。
  • 使用plot()方法绘制速度数据点。
  • 创建一个与 X 轴共享的双轴。
  • 使用plot()方法绘制加速数据点。
  • 在图表中放置图例。
  • 要显示图表,请使用show()方法。

示例

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

speed = np.array([3, 1, 2, 0, 5])
acceleration = np.array([6, 5, 7, 1, 5])

ax1 = plt.subplot()
l1, = ax1.plot(speed, color='red')
ax2 = ax1.twinx()
l2, = ax2.plot(acceleration, color='orange')

plt.legend([l1, l2], ["speed", "acceleration"])

plt.show()

输出

更新于: 10-6-2021

10K+ 浏览量

开启您的职业生涯

参加课程认证

入门
广告
© . All rights reserved.