jor*_*ris 256 python axis matplotlib legend
我有一个带有两个y轴的情节,使用twinx().我也给线条贴了标签,并希望用它们来展示legend(),但我只是成功地在图例中获得了一个轴的标签:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
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)
plt.show()
Run Code Online (Sandbox Code Playgroud)
所以我只得到图例中第一个轴的标签,而不是第二个轴的标签"temp".我怎么能将这第三个标签添加到图例中?

Pau*_*aul 314
您可以通过添加以下行来轻松添加第二个图例:
ax2.legend(loc=0)
Run Code Online (Sandbox Code Playgroud)
你会得到这个:

但是如果你想要一个传奇上的所有标签,那么你应该做这样的事情:
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.show()
Run Code Online (Sandbox Code Playgroud)
哪个会给你这个:

小智 160
我不确定此功能是否是新功能,但您也可以使用get_legend_handles_labels()方法,而不是自己跟踪行和标签:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
pi = np.pi
# fake data
time = np.linspace (0, 25, 50)
temp = 50 / np.sqrt (2 * pi * 3**2) \
* np.exp (-((time - 13)**2 / (3**2))**2) + 15
Swdown = 400 / np.sqrt (2 * pi * 3**2) * np.exp (-((time - 13)**2 / (3**2))**2)
Rn = Swdown - 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')
# ask matplotlib for the plotted objects and their labels
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, 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.show()
Run Code Online (Sandbox Code Playgroud)
Imp*_*est 54
从matplotlib 2.1版开始,您可以使用图例.可以创建图形图例ax.legend(),而不是使用轴的手柄ax生成图例
fig.legend(loc="upper right")
这将收集图中所有子图的所有句柄.由于它是一个图形图例,它将被放置在图的角落,并且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 = 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="upper right")
ax.set_xlabel("x [units]")
ax.set_ylabel(r"Quantity 1")
ax2.set_ylabel(r"Quantity 2")
plt.show()
Run Code Online (Sandbox Code Playgroud)
为了将图例放回轴中,可以提供a bbox_to_anchor和a bbox_transform.后者将是图例应该存在的轴的轴变换.前者可以是由loc轴坐标给定的边的坐标.
fig.legend(loc="upper right", bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)
Run Code Online (Sandbox Code Playgroud)
Syr*_*jor 35
您可以通过添加ax中的行来轻松获得所需内容:
ax.plot([], [], '-r', label = 'temp')
Run Code Online (Sandbox Code Playgroud)
要么
ax.plot(np.nan, '-r', label = 'temp')
Run Code Online (Sandbox Code Playgroud)
除了为斧头传说添加标签之外,这只会绘制一个标签.
我认为这是一种更容易的方法.当你在第二轴只有几条线时,没有必要自动跟踪线,因为像上面那样用手固定会很容易.无论如何,这取决于你需要什么.
整个代码如下:
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()
ax = fig.add_subplot(111)
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)")
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.show()
Run Code Online (Sandbox Code Playgroud)
情节如下:

更新:添加更好的版本:
ax.plot(np.nan, '-r', label = 'temp')
Run Code Online (Sandbox Code Playgroud)
这plot(0, 0)可能会改变轴范围.
Suu*_*hgi 19
import numpy as np
from matplotlib import pyplot as plt
fig, ax1 = plt.subplots( figsize=(15,6) )
Y1, Y2 = np.random.random((2,100))
ax2 = ax1.twinx()
Run Code Online (Sandbox Code Playgroud)
我很惊讶它到目前为止还没有出现,但最简单的方法是手动将它们收集到一个轴对象中(位于彼此之上)
l1 = ax1.plot( range(len(Y1)), Y1, label='Label 1' )
l2 = ax2.plot( range(len(Y2)), Y2, label='Label 2', color='orange' )
ax1.legend( handles=l1+l2 )
Run Code Online (Sandbox Code Playgroud)
或者让它们自动收集到周围的图形中fig.legend()并摆弄参数bbox_to_anchor:
ax1.plot( range(len(Y1)), Y1, label='Label 1' )
ax2.plot( range(len(Y2)), Y2, label='Label 2', color='orange' )
fig.legend( bbox_to_anchor=(.97, .97) )
Run Code Online (Sandbox Code Playgroud)
fig.tight_layout()
fig.savefig('stackoverflow.png', bbox_inches='tight')
Run Code Online (Sandbox Code Playgroud)
小智 6
快速入侵可能适合您的需求..
取下盒子的框架,手动将两个图例放在一起.像这样的东西......
ax1.legend(loc = (.75,.1), frameon = False)
ax2.legend( loc = (.75, .05), frameon = False)
Run Code Online (Sandbox Code Playgroud)
loc元组是从左到右和从下到上的百分比,表示图表中的位置.
我发现了一个以下官方matplotlib示例,它使用host_subplot在一个图例中显示多个y轴和所有不同的标签.没有必要的解决方法.迄今为止我发现的最佳解决方案 http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt
host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)
par1 = host.twinx()
par2 = host.twinx()
offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
axes=par2,
offset=(offset, 0))
par2.axis["right"].toggle(all=True)
host.set_xlim(0, 2)
host.set_ylim(0, 2)
host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)
host.legend()
plt.draw()
plt.show()
Run Code Online (Sandbox Code Playgroud)