Matplotlib:调整图例位置

2024-09-29 21:37:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个包含多个子块的图形。其中一个子块给我带来了一些麻烦,因为没有一个轴角或中心可以自由(或可以自由)放置图例。我想做的是将图例放置在“左上”和“左中”位置之间的某个位置,同时使其与y轴之间的填充与其他子批次中的图例(使用预定义的图例位置关键字之一放置)相等。

我知道我可以通过使用loc=(x,y)指定一个自定义位置,但是我不知道如何使图例和y轴之间的填充等于其他图例使用的填充。是否可以以某种方式使用第一个图例的borderaxespad属性?尽管我没能成功地让它发挥作用。

欢迎提出任何建议!

编辑:这里有一个(非常简单)的问题说明:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 2, sharex=False, sharey=False)
ax[0].axhline(y=1, label='one')
ax[0].axhline(y=2, label='two')
ax[0].set_ylim([0.8,3.2])
ax[0].legend(loc=2)

ax[1].axhline(y=1, label='one')
ax[1].axhline(y=2, label='two')
ax[1].axhline(y=3, label='three')
ax[1].set_ylim([0.8,3.2])
ax[1].legend(loc=2)

plt.show()

enter image description here

我想要的是右边的图例稍微向下移动,这样它就不再与线重叠。 作为最后的手段,我可以改变轴心的限制,但我非常想避免。


Tags: false图形pltaxoneloclabel子块
2条回答

在花了太多的时间在这上面之后,我提出了以下令人满意的解决方案(肯定有帮助的Transformations Tutorial):

bapad = plt.rcParams['legend.borderaxespad']
fontsize = plt.rcParams['font.size']
axline = plt.rcParams['axes.linewidth']  #need this, otherwise the result will be off by a few pixels
pad_points = bapad*fontsize + axline  #padding is defined in relative to font size
pad_inches = pad_points/72.0  #convert from points to inches
pad_pixels = pad_inches*fig.dpi  #convert from inches to pixels using the figure's dpi

然后,我发现以下两项都起作用,并为填充提供相同的值:

# Define inverse transform, transforms display coordinates (pixels) to axes coordinates
inv = ax[1].transAxes.inverted()
# Inverse transform two points on the display and find the relative distance
pad_axes = inv.transform((pad_pixels, 0)) - inv.transform((0,0))  
pad_xaxis = pad_axes[0]

或者

# Find how may pixels there are on the x-axis
x_pixels = ax[1].transAxes.transform((1,0)) - ax[1].transAxes.transform((0,0))
# Compute the ratio between the pixel offset and the total amount of pixels 
pad_xaxis = pad_pixels/x_pixels[0]

然后将图例设置为:

ax[1].legend(loc=(pad_xaxis,0.6))

绘图:

我看到你贴的答案,就试了一下。但问题是,它也取决于数字大小。

下面是一个新的尝试:

import numpy
import matplotlib.pyplot as plt


x = numpy.linspace(0, 10, 10000)
y = numpy.cos(x) + 2.

x_value = .014    #Offset by eye
y_value = .55

fig, ax = plt.subplots(1, 2, sharex = False, sharey = False)
fig.set_size_inches(50,30)

ax[0].plot(x, y, label = "cos")
ax[0].set_ylim([0.8,3.2])
ax[0].legend(loc=2)

line1 ,= ax[1].plot(x,y)
ax[1].set_ylim([0.8,3.2])

axbox = ax[1].get_position()

fig.legend([line1], ["cos"], loc = (axbox.x0 + x_value, axbox.y0 + y_value))

plt.show()

所以我现在做的基本上是从子块中得到坐标。然后根据整个图形的尺寸创建图例。因此,图形大小不再改变图例的位置。

使用x_valuey_value的值,图例可以定位在子批次中。x_value已被密切关注,以寻找与“正常”传说的良好对应。这个值可以根据你的意愿改变。y_value确定图例的高度。

enter image description here

祝你好运!

相关问题 更多 >

    热门问题