且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Matplotlib 绘制具有多个 x 和 y 轴的图形

更新时间:2023-01-22 17:41:39

use twinx() to show two axes, and convert the y_limits of ax1 in Celsius to y_limits of ax2 in Fahrenheit:

import matplotlib.pyplot as plt
from random import randint

x = range(1,24)
y = [randint(0,75) for x in x]

fig, ax1 = plt.subplots()

ax1.plot(x,y)
y_lim  = ax1.get_ylim()

y2_lim = [x*9/5 + 32 for x in y_lim]

ax2 = ax1.twinx()
ax2.set_ylim(y2_lim)

ax1.set_ylabel('deg C')
ax2.set_ylabel('deg F')

plt.show()