【问题标题】:Set a label's position in a pylab legend在 pylab 图例中设置标签的位置
【发布时间】:2023-04-01 16:52:01
【问题描述】:

我刚开始学习python,所以如果代码不是很合适,请告诉我。

我在一个情节的传说中得到了一小部分。但是由于标签的位置没有改变,所以看起来很奇怪:

我关于这个情节的代码如下:

datalist = [(np.loadtxt(filename, skiprows=1), label) for filename,label in list_of_files]

for data, label in datalist:
pylab.errorbar(abs(data[:,0]), abs(data[:,3]), yerr = data[:,4], fmt = 'o', label=r'$\frac{U_1+U_2}{2}$')

legend = pylab.legend(loc = 2, numpoints = 1)
frame = legend.get_frame()
frame.set_facecolor('0.95')
pylab.xlabel(r'I$\,$[$\mathrm{\mu}$A]')
pylab.ylabel('U [V]')
pylab.ylim([0,0.1])
pylab.show()

我使用范围是因为绘图中不同文件的值会更多,我只是想在添加其他数据之前修复标签的位置。

如何更改标签在图例中的位置?

【问题讨论】:

标签: python matplotlib


【解决方案1】:

也许您可以尝试以下方法。在 stackoverflow 上的另一个答案中找到它!

# Create legend
plt.plot(x, y, label = 'label_name')
leg = plt.legend( loc = 'upper right')

plt.draw() # Draw the figure so you can find the positon of the legend. 

# Get the bounding box of the original legend
bb = leg.get_bbox_to_anchor().inverse_transformed(ax.transAxes)

# Change to location of the legend. 
xOffset = 1.5
bb.x0 += xOffset
bb.x1 += xOffset
leg.set_bbox_to_anchor(bb, transform = ax.transAxes)


# Update the plot
plt.show()

点击这里了解更多信息:Move and resize legends-box in matplotlib

【讨论】:

    猜你喜欢
    • 2019-06-25
    • 2022-10-21
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多