`matplotlib`图形文本自动调整位置到左上角

问题描述 投票:0回答:1

当我运行以下代码时,没有任何问题。

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [4, 5, 6])
fig.text(
    0, 
    1,
    s = "ABCD",
    ha = "left",
    va = "bottom",
    transform = fig.transFigure
)
fig.patch.set_linewidth(5)
fig.patch.set_edgecolor("green")
plt.show()
plt.close()

我的目标是让

ABCD
位于左上角,高于图中其他所有内容并位于图中其他所有内容的左侧,而这正是发生的情况。

correct plot

当我运行这个时,出现问题。

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [4, 5, 6])
ax.set_ylabel("1\n2\n3\n4\n5\n6\n7")
ax.set_title("a\nb\nc\nd\ne\nf")
fig.text(
    0, 
    1,
    s = "ABCD",
    ha = "left",
    va = "bottom",
    transform = fig.transFigure
)
fig.patch.set_linewidth(5)
fig.patch.set_edgecolor("green")
plt.show()
plt.close()

incorrect plot

目标是使

ABCD
高于图中的其他所有内容,但标题显示得高于
ABCD
。同样,
ABCD
应该位于图中其他所有内容的左侧,但 y 轴标签位于
ABCD
的左侧。

奇怪的是,边框没有调整到图形的宽度或高度的问题,只是这个文本标签。

无论我如何处理轴标签或主标题,如何才能使

ABCD
文本标签显示在左上角?我需要文本的底部位于图中其他所有内容的上方,并且文本的右侧位于图中其他所有内容的左侧,就像我在第一张图片中一样。

python matplotlib plot graphics
1个回答
0
投票

我假设您正在使用笔记本或其他使用

bbox_inches="tight"
选项绘制图形的东西。 这会调整图形大小以适合其上的内容。 在这种情况下,文本会在调整大小完成之前放置,因此它略高于图形原始大小的左上角,但当图形扩展以适合所有内容时,文本不会移动。

如果您使用 annotate 而不是

text
,您将获得更多控制权,并且可以使用 xycoords 关键字将与任何现有艺术家相关的文本放置在图形上。 在这里,我将其相对于您的 y 标签的 x 坐标和相对于您的标题的 y 坐标放置:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [4, 5, 6])
yl = ax.set_ylabel("1\n2\n3\n4\n5\n6\n7")
t = ax.set_title("a\nb\nc\nd\ne\nf")
ax.annotate(
    "ABCD", 
    (0, 1),
    ha="left",
    va="bottom",
    xycoords=(yl, t)
)
fig.patch.set_linewidth(5)
fig.patch.set_edgecolor("green")
plt.savefig("test.png", bbox_inches="tight")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.