简体   繁体   English

将文本放在matplotlib图的左上角

[英]Putting text in top left corner of matplotlib plot

How can I put text in the top left (or top right) corner of a matplotlib figure, eg where a top left legend would be, or on top of the plot but in the top left corner?如何将文本放在 matplotlib 图形的左上角(或右上角),例如左上角图例所在的位置,或者在图的顶部但在左上角? Eg if it's a plt.scatter() , then something that would be within the square of the scatter, put in the top left most corner.例如,如果它是plt.scatter() ,那么将在散点图的正方形内的东西放在最左上角。

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.使用图例类型定位时,无论如何它都不应与任何散点图点重叠。

You can use text .您可以使用text

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: text坐标可以相对于轴给出,因此文本的位置将与绘图的大小无关:

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).默认转换指定文本在数据坐标中,或者,您可以在轴坐标中指定文本(0,0 是左下角,1,1 是右上角)。 The example below places text in the center of the axes::下面的示例将文本放置在轴的中心:

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.为了防止文本干扰你分散的任何点,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.更简单的方法是将 y_axis (ymax in ylim((ymin,ymax)) ) 设置为比您的点的最大 y 坐标高一点的值。 In this way you will always have this free space for the text.这样,您将始终拥有用于文本的空闲空间。

EDIT: here you have an example:编辑:这里有一个例子:

In [17]: from pylab import figure, text, scatter, show
In [18]: f = figure()
In [19]: ax = f.add_subplot(111)
In [20]: scatter([3,5,2,6,8],[5,3,2,1,5])
Out[20]: <matplotlib.collections.CircleCollection object at 0x0000000007439A90>
In [21]: text(0.1, 0.9,'matplotlib', ha='center', va='center', transform=ax.transAxes)
Out[21]: <matplotlib.text.Text object at 0x0000000007415B38>
In [22]:

在此处输入图像描述

The ha and va parameters set the alignment of your text relative to the insertion point. ha 和 va 参数设置文本相对于插入点的对齐方式。 ie. 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. ha='left' 是一个很好的设置,可以防止在手动缩小(变窄)框架时长文本超出左轴。

  • matplotlib is somewhat different from when the original answer was posted matplotlib与发布原始答案时有些不同
  • matplotlib.pyplot.text
  • matplotlib.axes.Axes.text
  • This answer is relevant to seaborn, which is a high-level api for matplotlib.这个答案与 seaborn 相关,它是 matplotlib 的高级 api。
  • Tested in python 3.10 , matplotlib 3.5.1 , seaborn 0.11.2python 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')

Output of Both两者的输出

在此处输入图像描述

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 axes-level plot seaborn轴水平图

import seaborn as sns

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

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

在此处输入图像描述

seaborn figure-level plot 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')

在此处输入图像描述

One solution would be to use the plt.legend function, even if you don't want an actual legend.一种解决方案是使用plt.legend函数,即使您不需要实际的图例。 You can specify the placement of the legend box by using the loc keyterm.您可以使用loc关键字指定图例框的位置。 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.请注意,因为loc=2 ,所以图例位于图的左上角。 And if the text overlaps with the plot, you can make it smaller by using legend.fontsize , which will then make the legend smaller.如果文本与绘图重叠,您可以使用legend.fontsize使其更小,这将使图例更小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM