修改图例的位置。

huangapple go评论70阅读模式
英文:

Modify the legend placement of a figure

问题

我使用一个返回matplotlib.figure对象和图例的程序包。我想要更改图例的边界框和位置。在查看了https://matplotlib.org/stable/api/figure_api.html后,我尝试按照以下方式检索图例:

ax = f.axes[0]
lgd_f = f.legend()
lgd = ax.get_legend_handles_labels()
print(lgd_f)
print(lgd)
ax.get_legend().set_bbox_to_anchor((1, 1.05))
ax.legend(bbox_to_anchor=(1, 1.05), loc=8)

然而,这并没有像预期的那样起作用,因为在轴上调用get_legend_handles_labels方法会返回两个空列表。不幸的是,无法修改程序包的内部。假设这是可能的,你能指导我正确的方向吗?

英文:

I am using a package program that return me a matplotlib.figure object together with a legend. I want to change the bounding box and placement of the legend. After checking https://matplotlib.org/stable/api/figure_api.html I tried to retrieve the legend as follows:

ax = f.axes[0]
lgd_f = f.legend()
lgd = ax.get_legend_handles_labels()
print(lgd_f)
print(lgd)
ax.get_legend().set_bbox_to_anchor((1, 1.05))
ax.legend(bbox_to_anchor=(1, 1.05), loc=8)

However, this did not work as expected as calling the get_legend_handles_labels method on the axes returns two empty lists. Unfortunately it is not possible to modify the internals of the package program. Assuming this is possible could you point me in the right direction?

答案1

得分: 3

The OP在this comment中表示他们遇到了"空列表"的问题。幸运的是,我没有遇到这个问题。

解决方案来自于OP发布的代码,唯一的问题是将图例的位置从默认值(0)更改为请求的位置 — 使用了图例对象的私有方法来解决。

修改图例的位置。

import matplotlib.pyplot as plt

def plot():
    f, a = plt.subplots()
    a.plot((0,1),(0,1), label='SW-NE')
    a.plot((0,1),(1,0), label='NW-SE')
    plt.legend()
    return f

f = plot()
a = f.axes[0]
l = a.get_legend()
l.set_bbox_to_anchor((1, 1.05))
l._set_loc(8) # "private" method
f.set_layout_engine('constrained')
plt.show()
英文:

The OP stated in this comment that they had a problem with "empty lists". Fortunately I experienced no such problem.

The solution follows from the code the OP posted, the only issue being changing the location of the Legend from default (0) to the requested one — solved using a private method of the Legend object.

修改图例的位置。

import matplotlib.pyplot as plt

def plot():
    f, a = plt.subplots()
    a.plot((0,1),(0,1), label='SW-NE')
    a.plot((0,1),(1,0), label='NW-SE')
    plt.legend()
    return f

f = plot()
a = f.axes[0]
l = a.get_legend()
l.set_bbox_to_anchor((1, 1.05))
l._set_loc(8) # "private" method
f.set_layout_engine('constrained')
plt.show()

huangapple
  • 本文由 发表于 2023年5月22日 06:44:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定