【4.1.2】matplotlib-绘制双Y轴曲线图

要点就是ax2 = ax1.twinx(), 制作一个兄弟轴

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0., np.e, 0.01)
y1 = np.exp(-x)
y2 = np.log(x)

fig = plt.figure()

ax1 = fig.add_subplot(111)
ax1.plot(x, y1)
ax1.set_ylabel('Y values for exp(-x)')
ax1.set_title("Double Y axis")

ax2 = ax1.twinx()  # this is the important function
ax2.plot(x, y2, 'r')
ax2.set_xlim([0, np.e])
ax2.set_ylabel('Y values for ln(x)')
ax2.set_xlabel('Same X for both exp(-x) and ln(x)')

plt.show()

二、我的案例

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0., np.e, 0.01)
y1 = np.exp(-x)
y2 = np.log(x)

# fig = plt.figure()
fig =plt.figure(figsize=(14,8))

ax1 = fig.add_subplot(111)
ax1.plot(x, y1)

ax1.set_ylabel('Y values for exp(-x)',fontsize=20)
ax1.set_title("Double Y axis",fontsize=20, rotation=45)

ax2 = ax1.twinx()  # this is the important function
ax2.plot(x, y2, 'r')
ax2.set_xlim([0, np.e])
ax2.set_ylabel('Y values for ln(x)',fontsize=20)

ax1.set_xlabel('Same X for both exp(-x) and ln(x),zzzz',fontsize=15)

ax1.tick_params(axis='both', which='major', labelsize=15)
ax2.tick_params(axis='both', which='major', labelsize=15)


for label in ax1.get_xticklabels():
    label.set_ha("right")
    label.set_rotation(45)
    
plt.show()
这里是一个广告位,,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn