将文本放在 matplotlib 图的左上角

发布于 2024-12-20 19:08:35 字数 234 浏览 2 评论 0原文

如何将文本放置在 matplotlib 图形的左上角(或右上角),例如左上角图例所在的位置,或者放置在绘图顶部但位于左上角?例如,如果它是一个plt.scatter(),那么将位于散点正方形内的东西放在最左上角。

例如,我想在不理想地知道所绘制的散点图的比例的情况下执行此操作,因为它会随着数据集的不同而变化。我只是希望文本大致位于左上角,或大致位于右上角。对于图例类型定位,无论如何它都不应该与任何散点图点重叠。

How can I put text in the top left (or top right) corner of a matplotlib figure, e.g. where a top left legend would be, or on top of the plot but in the top left corner? E.g. if it's a plt.scatter(), then something that would be within the square of the scatter, put in the top left most corner.

I'd like to do this without ideally knowing the scale of the scatterplot being plotted for example, since it will change from dataset to data set. I just want it the text to be roughly in the upper left, or roughly in the upper right. With legend type positioning it should not overlap with any scatter plot points anyway.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

鸩远一方 2024-12-27 19:08:36

您可以使用 文本

plt.text(x, y, s, fontsize=12)

text 坐标可以相对于轴给出,因此文本的位置将独立于绘图的大小:

默认转换指定文本位于数据坐标中,
或者,您可以在轴坐标中指定文本(0,0 是左下角
1,1 位于右上角)。下面的示例将文本放置在中心
轴数::

plt.text(0.5, 0.5, 'matplotlib',
     horizontalalignment='center',
     verticalalignment='center',
     transform = ax.transAxes)

要防止文本干扰分散的任何点,据我所知是更困难的。更简单的方法是将 y_axis(ylim((ymin,ymax)) 中的 ymax)设置为比点的最大 y 坐标稍高的值。这样,您将始终拥有用于文本的可用空间。

编辑:这里有一个示例:

from matplotlib import pyplot as plt

f, ax = plt.subplots()
plt.scatter([3,5,2,6,8],[5,3,2,1,5])
plt.text(.01, .99, 'matplotlib', ha='left', va='top', transform=ax.transAxes)
f.tight_layout()

plot

hava 参数设置文本相对于插入点的对齐方式。 IE。 ha='left' 是一个很好的设置,可以防止手动缩小(变窄)框架时长文本超出左轴。

You can use text.

plt.text(x, y, s, fontsize=12)

text coordinates can be given relative to the axis, so the position of your text will be independent of the size of the plot:

The default transform specifies that text is in data coords,
alternatively, you can specify text in axis coords (0,0 is lower-left
and 1,1 is upper-right). The example below places text in the center
of the axes::

plt.text(0.5, 0.5, 'matplotlib',
     horizontalalignment='center',
     verticalalignment='center',
     transform = ax.transAxes)

To prevent the text to interfere with any point of your scatter is more difficult afaik. The easier method is to set y_axis (ymax in ylim((ymin,ymax))) to a value a bit higher than the max y-coordinate of your points. In this way you will always have this free space for the text.

EDIT: here you have an example:

from matplotlib import pyplot as plt

f, ax = plt.subplots()
plt.scatter([3,5,2,6,8],[5,3,2,1,5])
plt.text(.01, .99, 'matplotlib', ha='left', va='top', transform=ax.transAxes)
f.tight_layout()

plot

The ha and va parameters set the alignment of your text relative to the insertion point. ie. ha='left' is a good set to prevent a long text to go out of the left axis when the frame is reduced (made narrower) manually.

执着的年纪 2024-12-27 19:08:36
  • matplotlib 与发布原始答案时有所不同。
  • matplotlib.pyplot.text
  • < a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.text.html" rel="noreferrer">matplotlib.axes.Axes.text
  • 这个答案与seaborn相关,seaborn是matplotlib的高级API。
  • python 3.10matplotlib 3.5.1seaborn 0.11.2中测试
import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')

# or 

fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')

"

输入图像描述这里

import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)


ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)

ax.text(right, 0.5 * (bottom + top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

plt.axis('off')

plt.show()

在此处输入图像描述

seaborn 轴级图

import seaborn as sns

# sample dataframe
flights = sns.load_dataset("flights")

fig, ax = plt.subplots(figsize=(6, 6))
sns.lineplot(data=flights, x="year", y="passengers", ax=ax)
ax.text(1950, 500, 'flights with CI', size=15, color='purple')

在此处输入图像描述

seaborn 图形级图

tips = sns.load_dataset('tips')

g = sns.relplot(data=tips, x="total_bill", y="tip", hue="day", col="time")

# iterate through each axes
for ax in g.axes.flat:
    
    ax.text(10, 9, "Who's Hungy?", size=15, color='purple')

在此处输入图像描述

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')

# or 

fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')

Output of Both

enter image description here

import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)


ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)

ax.text(right, 0.5 * (bottom + top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

plt.axis('off')

plt.show()

enter image description here

seaborn axes-level plot

import seaborn as sns

# sample dataframe
flights = sns.load_dataset("flights")

fig, ax = plt.subplots(figsize=(6, 6))
sns.lineplot(data=flights, x="year", y="passengers", ax=ax)
ax.text(1950, 500, 'flights with CI', size=15, color='purple')

enter image description here

seaborn figure-level plot

tips = sns.load_dataset('tips')

g = sns.relplot(data=tips, x="total_bill", y="tip", hue="day", col="time")

# iterate through each axes
for ax in g.axes.flat:
    
    ax.text(10, 9, "Who's Hungy?", size=15, color='purple')

enter image description here

方圜几里 2024-12-27 19:08:36

一种解决方案是使用 plt.legend 函数,即使您不需要实际的图例。您可以使用 loc 关键字指定图例框的位置。更多信息可以在此网站找到,但我还提供了一个示例,展示了如何放置图例:

ax.scatter(xa,ya, marker='o', s=20, c="lightgreen", alpha=0.9)
ax.scatter(xb,yb, marker='o', s=20, c="dodgerblue", alpha=0.9)
ax.scatter(xc,yc marker='o', s=20, c="firebrick", alpha=1.0)
ax.scatter(xd,xd,xd, marker='o', s=20, c="goldenrod", alpha=0.9)
line1 = Line2D(range(10), range(10), marker='o', color="goldenrod")
line2 = Line2D(range(10), range(10), marker='o',color="firebrick")
line3 = Line2D(range(10), range(10), marker='o',color="lightgreen")
line4 = Line2D(range(10), range(10), marker='o',color="dodgerblue")
plt.legend((line1,line2,line3, line4),('line1','line2', 'line3', 'line4'),numpoints=1, loc=2) 

请注意,由于 loc=2,图例位于图的左上角。如果文本与绘图重叠,您可以使用legend.fontsize 将其变小,这将使图例变小。

One solution would be to use the plt.legend function, even if you don't want an actual legend. You can specify the placement of the legend box by using the loc keyterm. More information can be found at this website but I've also included an example showing how to place a legend:

ax.scatter(xa,ya, marker='o', s=20, c="lightgreen", alpha=0.9)
ax.scatter(xb,yb, marker='o', s=20, c="dodgerblue", alpha=0.9)
ax.scatter(xc,yc marker='o', s=20, c="firebrick", alpha=1.0)
ax.scatter(xd,xd,xd, marker='o', s=20, c="goldenrod", alpha=0.9)
line1 = Line2D(range(10), range(10), marker='o', color="goldenrod")
line2 = Line2D(range(10), range(10), marker='o',color="firebrick")
line3 = Line2D(range(10), range(10), marker='o',color="lightgreen")
line4 = Line2D(range(10), range(10), marker='o',color="dodgerblue")
plt.legend((line1,line2,line3, line4),('line1','line2', 'line3', 'line4'),numpoints=1, loc=2) 

Note that because loc=2, the legend is in the upper-left corner of the plot. And if the text overlaps with the plot, you can make it smaller by using legend.fontsize, which will then make the legend smaller.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文