将文本放在 matplotlib 绘图的左上角

编程入门 行业动态 更新时间:2024-10-24 10:22:44
本文介绍了将文本放在 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.

谢谢!

推荐答案

您可以使用 text.

You can use text.

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

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:

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

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::

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

要防止文本干扰您散布的任何一点是更加困难的afaik.更简单的方法是将 y_axis(ylim((ymin,ymax)) 中的 ymax)设置为比点的最大 y 坐标稍高的值.通过这种方式,您将始终拥有该文本的可用空间.

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.

这里有一个例子:

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]:

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

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.

更多推荐

将文本放在 matplotlib 绘图的左上角

本文发布于:2023-07-18 04:49:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1141168.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:放在   左上角   文本   matplotlib

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!