如何在 Matplotlib 中的第二 Y 轴上添加 Y 轴标签

Suraj Joshi 2024年2月15日

与轴对象直接交互

``````import numpy as np
import matplotlib.pyplot as plt

a = np.linspace(0, 5, 100)

y1 = np.sin(2 * np.pi * a)
y2 = np.cos(2 * np.pi * a)

fig, ax1 = plt.subplots()

ax1.set_xlabel("time (s)")
ax1.set_ylabel("sin", color="red")
ax1.plot(a, y1, color=color)
ax1.tick_params(axis="y", labelcolor=color)

ax2 = ax1.twinx()
ax2.set_ylabel("cos", color="green")
ax2.plot(a, y2, color=color)
ax2.tick_params(axis="y", labelcolor=color)

fig.tight_layout()
plt.show()
``````

``````ax2 = ax1.twinx()
``````

`Axes.twinx()` 创建一个新的 `Axes`，其 Y 轴与原始轴相反，在本例中为 `ax1`

使用 `DataFrame.plot` 方法将 y 轴标签添加到辅助 y 轴

``````import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
{
"Age": [22, 12, 18, 25, 30],
"Height": [155, 129, 138, 164, 145],
"Weight": [60, 40, 45, 55, 60],
}
)
ax = df.plot(kind="line", x="Age", y="Height", color="DarkBlue")

ax2 = df.plot(kind="line", x="Age", y="Weight", secondary_y=True, color="Red", ax=ax)

ax.set_ylabel("Height")
ax2.set_ylabel("Weight")
plt.tight_layout()
plt.show()
``````

Suraj Joshi is a backend software engineer at Matrice.ai.