# 如何在 Matplotlib 中的第二 Y 軸上新增 Y 軸標籤

Suraj Joshi 2023年1月30日

## 與軸物件直接互動

``````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.