将文本放在 matplotlib 图的左上角
如何将文本放置在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
文本
。text
坐标可以相对于轴给出,因此文本的位置将独立于绘图的大小:要防止文本干扰分散的任何点,据我所知是更困难的。更简单的方法是将 y_axis(
ylim((ymin,ymax))
中的 ymax)设置为比点的最大 y 坐标稍高的值。这样,您将始终拥有用于文本的可用空间。编辑:这里有一个示例:
ha
和va
参数设置文本相对于插入点的对齐方式。 IE。ha='left'
是一个很好的设置,可以防止手动缩小(变窄)框架时长文本超出左轴。You can use
text
.text
coordinates can be given relative to the axis, so the position of your text will be independent of the size of the plot: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:
The
ha
andva
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.matplotlib
与发布原始答案时有所不同。matplotlib.pyplot.text
matplotlib.axes.Axes.text
python 3.10
、matplotlib 3.5.1
、seaborn 0.11.2
中测试"
seaborn 轴级图
seaborn 图形级图
matplotlib
is somewhat different from when the original answer was posted.matplotlib.pyplot.text
matplotlib.axes.Axes.text
python 3.10
,matplotlib 3.5.1
,seaborn 0.11.2
Output of Both
seaborn axes-level plot
seaborn figure-level plot
一种解决方案是使用 plt.legend 函数,即使您不需要实际的图例。您可以使用
loc
关键字指定图例框的位置。更多信息可以在此网站找到,但我还提供了一个示例,展示了如何放置图例:请注意,由于
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 theloc
keyterm. More information can be found at this website but I've also included an example showing how to place a legend: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 usinglegend.fontsize
, which will then make the legend smaller.