首页 > 解决方案 > 管理图例中标签的显示

问题描述

我正在尝试在一个情节中绘制多个系列。在这近 10 个系列中,还有 2 个更重要。我想让图例中的标签在图下的几行中显示(使用ncols图例的参数),但我希望第一行只有这两个更重要的标签。可能吗?

标签: pythonmatplotlibplotlegend

解决方案


您可以简单地排列 ax.plot 语句的顺序,以获得图例第一行的重要图例。在以下示例中,三次和对数图例是我们希望出现在第一行的图例。

import math
x_data = list(range(1,10))
y1 = [3*x for x in x_data]
y2 = [x**2 for x in x_data]
y3 = [x**3 for x in x_data]
y4 = [math.log10(x) for x in x_data]
y5 = [x*math.log10(x) for x in x_data]

fig, ax = plt.subplots()
ax.plot(x_data,y3, label= 'Cubic')#important 1
ax.plot(x_data,y1, label= 'Linear')
ax.plot(x_data,y2, label= 'Quadratic')
ax.plot(x_data,y4, label= 'Logarithmic')#important 2
ax.plot(x_data,y5, label = 'x log x')

fig.legend(loc = 'upper center',
           bbox_to_anchor = (0.5,0.8),
           ncol = 2)
plt.show()

在此处输入图像描述

更新:要在第一行有 2 个图例项,其余在第二行,您需要有两个单独的图例。实现这一点的最佳方法是拥有双 y 轴,并将重要数据绘制在一个轴上,其余数据绘制在另一个轴上。然后,您必须确保将 y 限制设置为彼此相等,并为每个数据集指定一种颜色。这允许您为第一个轴图例设置 ncol = 2,为另一个轴图例设置其他数字。最后,您可以利用 legend() 中的许多参数使两个图例看起来像一个。方法如下:

import math
x_data = list(range(1,10))
y1 = [3*x for x in x_data]
y2 = [x**2 for x in x_data]
y3 = [x**3 for x in x_data]
y4 = [math.log10(x) for x in x_data]
y5 = [x*math.log10(x) for x in x_data]

fig = plt.figure(figsize=(12,5))
fig.suptitle("Title")
ax1 = fig.add_subplot()
ax2 = ax1.twinx()

ax1.plot(x_data,y3, label= 'Cubic', color = 'blue')#important 1
ax1.plot(x_data,y4, label= 'Logarithmic', color = 'orange')#important 2

ax2.plot(x_data,y1, label= 'Linear', color = 'red')
ax2.plot(x_data,y2, label= 'Quadratic', color = 'green')
ax2.plot(x_data,y5, label = 'x log x', color = 'purple')

ax2.set_ylim(ax1.get_ylim()) #set the ylimits to be equal for both y axes

ax1.legend(loc = 'upper center',
           bbox_to_anchor = (0.5,0.91),
           edgecolor = 'none',
           facecolor = 'grey',
           framealpha = 0.3,
           ncol = 2)
ax2.legend(loc = 'upper center',
           bbox_to_anchor = (0.5,0.85),
           edgecolor = 'none',
           facecolor = 'grey',
           framealpha = 0.3,
           ncol = 3)

plt.show()

在此处输入图像描述


推荐阅读