【Python】matplotlib 双y轴绘制及合并图例

时间:2022-07-04 17:09:26

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)
plt.savefig('0.png')

  每个句柄对应一个图例。

【Python】matplotlib 双y轴绘制及合并图例

2. 合并图例

  1) 仅使用一个轴的legend()函数

 # -*- 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)
plt.savefig('0.png')

  可以看到y1轴和y2轴的图例已经合并了

【Python】matplotlib 双y轴绘制及合并图例

  2)使用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) ax.set_xlabel("x [units]")
ax.set_ylabel(r"Quantity 1")
ax2.set_ylabel(r"Quantity 2") plt.savefig('0.png')

  可以看到图例位置不对,已经出界,需要使用bbox_to_anchor和bbox_transform设置。

  fig.legend(loc=1, bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)

【Python】matplotlib 双y轴绘制及合并图例

 # -*- 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") plt.savefig('0.png')

   可以看到图例已经正常了。

【Python】matplotlib 双y轴绘制及合并图例

转自:*