python - 管理图例中标签的显示
问题描述
我正在尝试在一个情节中绘制多个系列。在这近 10 个系列中,还有 2 个更重要。我想让图例中的标签在图下的几行中显示(使用ncols
图例的参数),但我希望第一行只有这两个更重要的标签。可能吗?
解决方案
您可以简单地排列 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()
推荐阅读
- css - 如何修复:Sass/CSS 正在编译但未加载到浏览器元素中
- python - 将更改日期的电子邮件主题行添加到“接受的主题”列表中
- grails - 如何将数组值从 LInkedHashMap 转换为 List?
- android - 如何从 json 对象数组中通过 id 获取特定对象?
- sql-server - 在 SQL Server 中删除行只有一列为零
- c# - 是否有任何理由在 Task.Run 中运行异步代码?
- python - AttributeError:“pywintypes.datetime”对象没有属性“纳秒”
- sql-server-2012 - 从 60 个外键引用的表中删除记录
- objective-c - 错误代码=2“无法连接到 iTunes Store”{NSLocalizedDescription=无法连接到 iTunes Store} 仅适用于部分用户的生产环境
- typescript - 修复动态访问对象值时的类型错误,即 myObject[`VALUE_${variable}`]