【问题标题】:Swap some labels in legend - matplotlib交换图例中的一些标签 - matplotlib
【发布时间】:2020-04-21 13:18:59
【问题描述】:

考虑以下示例:

import matplotlib.pyplot as plt
import numpy as np


fig = plt.figure(figsize=(4,6))
axis = fig.add_subplot(111)
x = np.linspace(1,2,100)
axis.plot(x, x, label = "a")
axis.plot(x, x**2, label = "b")
axis.plot(x, x**3, label = "c")
axis.plot(x, x**4, label = "d")
axis.legend()

plt.show()

有没有一种简单的方法可以在不更改代码顺序的情况下相互交换第一个对象(a 用蓝线)和最后一个对象(d 用红线)。因此,图例应显示顺序(从上到下):

  • 红线d
  • 橙线b
  • 绿线c
  • 蓝色处理一个

【问题讨论】:

  • 您也可以在plot() 函数中提及绘图的颜色。 axis.plot(x, x, '#0f0f0f', label="a") 在这种情况下,十六进制颜色代码已用于选择颜色。更多选项可以查看matplotlib.org/3.1.1/tutorials/colors/colors.html
  • 我可能说错了。我想交换图例中的第一个和最后一个对象(= 彩色线 + 文本)

标签: python matplotlib legend


【解决方案1】:

您可以使用get_legend_handles_labels 获取图例的句柄和标签,并按上述顺序重置它们:

import matplotlib.pyplot as plt
import numpy as np


fig = plt.figure(figsize=(16,10))
axis = fig.add_subplot(111)
x = np.linspace(1,2,100)
axis.plot(x, x, label = "a")
axis.plot(x, x**2, label = "b")
axis.plot(x, x**3, label = "c")
axis.plot(x, x**4, label = "d")

axis.legend()
handles, labels = axis.get_legend_handles_labels()
axis.legend([handles[-1]] + handles[1:-1] + [handles[0]], 
            [labels[-1]] + labels[1:-1] + [labels[0]])

plt.show()

【讨论】:

    猜你喜欢
    • 2017-06-28
    • 2017-08-12
    • 2014-11-26
    • 2017-03-03
    • 2016-12-07
    • 2019-05-28
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多