首页 > 其他分享 >matplotlib 双y轴绘制及合并图例

matplotlib 双y轴绘制及合并图例

时间:2022-10-21 09:24:20浏览次数:70  
标签:ax2 10 set random matplotlib 图例 np ax 绘制

1.双y轴绘制 关键函数:twinx()

 # -*- coding: utf-8 -*-
 import numpy as np
 import matplotlib.pyplot as plt
 from matplotlib import rc
 rc('mathtext', default='regular') 

 time = np.arange(10)
 temp = np.random.random(10)*30
 Swdown = np.random.random(10)*100-10
 Rn = np.random.random(10)*100-10 

 fig = plt.figure()
 ax = fig.add_subplot(111)
 ax.plot(time, Swdown, '-', label = 'Swdown')
 ax.plot(time, Rn, '-', label = 'Rn')
 ax2 = ax.twinx()
 ax2.plot(time, temp, '-r', label = 'temp')
 ax.legend(loc=0)
 ax.grid()
 ax.set_xlabel("Time (h)")
 ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
 ax2.set_ylabel(r"Temperature ($^circ$C)")
 ax2.set_ylim(0, 35)
 ax.set_ylim(-20,100)
 ax2.legend(loc=0)

合并图例

# -*- coding: utf-8 -*-
 import numpy as np
 import matplotlib.pyplot as plt
 from matplotlib import rc
 rc('mathtext', default='regular') 

 time = np.arange(10)
 temp = np.random.random(10)*30
 Swdown = np.random.random(10)*100-10
 Rn = np.random.random(10)*100-10
 

 fig = plt.figure()
 ax = fig.add_subplot(111) 

 lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
 lns2 = ax.plot(time, Rn, '-', label = 'Rn')
 ax2 = ax.twinx()
 lns3 = ax2.plot(time, temp, '-r', label = 'temp')
 

 # added these three lines
 lns = lns1+lns2+lns3
 labs = [l.get_label() for l in lns]
 ax.legend(lns, labs, loc=0)
 

 ax.grid()
 ax.set_xlabel("Time (h)")
 ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
 ax2.set_ylabel(r"Temperature ($^circ$C)")
 ax2.set_ylim(0, 35)
 ax.set_ylim(-20,100)

使用Figure.legend()

 # -*- coding: utf-8 -*-
 import numpy as np
 import matplotlib.pyplot as plt 

 x = np.linspace(0,10)
 y = np.linspace(0,10)
 z = np.sin(x/3)**2*98 

 fig = plt.figure()
 ax = fig.add_subplot(111)
 ax.plot(x,y, '-', label = 'Quantity 1') 

 ax2 = ax.twinx()
 ax2.plot(x,z, '-r', label = 'Quantity 2')
 fig.legend(loc=1, bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)
 

 ax.set_xlabel("x [units]")
 ax.set_ylabel(r"Quantity 1")
 ax2.set_ylabel(r"Quantity 2")

标签:ax2,10,set,random,matplotlib,图例,np,ax,绘制
From: https://www.cnblogs.com/conpi/p/16812311.html

相关文章