/ 猿问

带有twinx（）的辅助轴：如何添加到图例？

2019-08-23 15:52:56

import numpy as np

import matplotlib.pyplot as plt

from matplotlib import rc

rc('mathtext', default='regular')

fig = plt.figure()

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)")

ax2.set_ylabel(r"Temperature (\$^\circ\$C)")

ax2.set_ylim(0, 35)

ax.set_ylim(-20,100)

plt.show()

3 回答

`ax2.legend(loc=0)`

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()

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')

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)")

ax2.set_ylabel(r"Temperature (\$^\circ\$C)")

ax2.set_ylim(0, 35)

ax.set_ylim(-20,100)

plt.show()

fig.legend（loc =“右上角”）

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.plot(x,y, '-', label = 'Quantity 1')

ax2 = ax.twinx()

ax2.plot(x,z, '-r', label = 'Quantity 2')

fig.legend(loc="upper right")

ax.set_xlabel("x [units]")

ax.set_ylabel(r"Quantity 1")

ax2.set_ylabel(r"Quantity 2")

plt.show()

`fig.legend(loc="upper right", bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)`

ax.plot(0, 0, '-r', label = 'temp')

ax.plot(np.nan, '-r', label = 'temp')

import numpy as np

import matplotlib.pyplot as plt

from matplotlib import rc

rc('mathtext', default='regular')

time = np.arange(22.)

temp = 20*np.random.rand(22)

Swdown = 10*np.random.randn(22)+40

Rn = 40*np.random.rand(22)

fig = plt.figure()

ax2 = ax.twinx()

#---------- look at below -----------

ax.plot(time, Swdown, '-', label = 'Swdown')

ax.plot(time, Rn, '-', label = 'Rn')

ax2.plot(time, temp, '-r')  # The true line in ax2

ax.plot(np.nan, '-r', label = 'temp')  # Make an agent in ax

ax.legend(loc=0)

#---------------done-----------------

ax.grid()

ax.set_xlabel("Time (h)")

ax2.set_ylabel(r"Temperature (\$^\circ\$C)")

ax2.set_ylim(0, 35)

ax.set_ylim(-20,100)

plt.show()

`ax.plot(np.nan, '-r', label = 'temp')`

`plot(0, 0)`可能会改变轴范围。

• 3 回答
• 0 关注
• 444 浏览

0/150