# Matplotlib 中的 twinx 和 twiny

Suraj Joshi 2024年2月15日

## 在 Python Matplotlib 中使用 `matplotlib.axes.Axes.twinx()`

``````import matplotlib.pyplot as plt

students = ["Anil", "Sohit", "Hrishav", "Ayush", "Sunil"]
heights_in_cms = [165, 160, 140, 150, 130]

fig, axes = plt.subplots()
fig.set_size_inches(8, 6)
axes.bar(students, heights_in_cms)
y1, y2 = axes.get_ylim()
axes.set_xlabel("Students", fontsize=12)
axes.set_ylabel("Height in cms", fontsize=12)

twin_axes = axes.twinx()
twin_axes.set_ylim(y1 * 0.394, y2 * 0.394)
twin_axes.set_ylabel("Height in Inches", fontsize=12)

fig.suptitle("Plot using matplotlib.axes.Axes.twinx()", fontsize=15)
plt.show()
``````

## Matplotlib Python 中的 `matplotlib.axes.Axes.twiny()`

``````import matplotlib.pyplot as plt

distance_in_kms = [10, 20, 30, 40, 50]
fare_in_dollars = [2, 3.5, 5, 7, 10]

fig, axes = plt.subplots()
fig.set_size_inches(10, 8)
axes.plot(distance_in_kms, fare_in_dollars)
x1, x2 = axes.get_xlim()
axes.set_xlabel("Distance in kms", fontsize=12)
axes.set_ylabel("Fare (\$)", fontsize=12)

twin_axes = axes.twiny()
twin_axes.set_xlim(x1 * 0.62, x2 * 0.62)
twin_axes.set_xlabel("Distance in miles", fontsize=12)

fig.suptitle("Plot using matplotlib.axes.Axes.twiny()", fontsize=15)
plt.show()
``````

## Matplotlib 中一起使用 `twinx()` 和 `twiny()`

``````import matplotlib.pyplot as plt

distance_in_kms = [10, 20, 30, 40, 50]
fare_in_dollars = [2, 3.5, 5, 7, 10]

fig, axes = plt.subplots()
fig.set_size_inches(10, 8)
axes.plot(distance_in_kms, fare_in_dollars)
x1, x2 = axes.get_xlim()
y1, y2 = axes.get_ylim()
axes.set_xlabel("Distance in kms", fontsize=12)
axes.set_ylabel("Fare (\$)", fontsize=12)

twin_axes = axes.twinx().twiny()

twin_axes.set_ylim(y1 * 0.85, y2 * 0.85)
twin_axes.set_ylabel("Fare in Euros", fontsize=12)

twin_axes.set_xlim(x1 * 0.62, x2 * 0.62)
twin_axes.set_xlabel("Distance in miles", fontsize=12)

fig.suptitle("Matplotlib use twinx() and twiny() together", fontsize=15)
plt.show()
``````

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