【问题标题】:How to display a text with matplotlib?如何使用 matplotlib 显示文本?
【发布时间】:2023-03-17 17:37:01
【问题描述】:

我想这样做:

我有这个 python 代码:

import numpy as np
import pylab as plt

a = np.array([1,2,3,4,5,6,7,8,9,10])
b = np.array([7,8,6,3,2,1,5,8,4,15])
c = plt.plot(a,b,'.')
d = 5
plt.text(2,3, "d = "+d) #This line is the problem because i have not the value of d !
plt.show()

所以实际上我只想显示 d 的值,我也想显示 d 的值,但相对而言,例如在右下角而不是某些坐标。可以用 Python 做到这一点吗?

非常感谢!

【问题讨论】:

    标签: python python-2.7 python-3.x numpy matplotlib


    【解决方案1】:

    例如,您可以使用 transform 参数放置在从 0.01.0 的相对坐标中

    plt.text(0.5,
             0.67,
             "d = {}".format(d),
             transform=plt.gca().transAxes)
    

    在这个本地系统中,(0, 0) 是左下角,(1, 1) 是图的右上角。 Here is a good reference 用于在绘图的不同位置放置和旋转文本。

    【讨论】:

      【解决方案2】:

      文字

      您可以使用text 在图中放置文本。默认情况下,坐标是数据坐标,但您可以指定一个转换来切换,例如到轴坐标。

      plt.text(.96,.94,"d={}".format(d), bbox={'facecolor':'w','pad':5},
               ha="right", va="top", transform=plt.gca().transAxes )
      

      注释

      您可以使用annotate 在图中某处生成文本。与text 相比的优势在于,您可以 (a) 使用额外的箭头指向一个对象,以及 (b) 您可以用简单的字符串而不是转换来指定坐标系。

      plt.annotate("d={}".format(d), xy=(p, 15), xytext=(.96,.94), 
                  xycoords="data", textcoords="axes fraction",
                  bbox={'facecolor':'w','pad':5}, ha="right", va="top")
      

      锚定文本

      您可以使用来自 offsetbox 的AnchoredText

      from matplotlib.offsetbox import AnchoredText
      a = AnchoredText("d={}".format(d), loc=1, pad=0.4, borderpad=0.5)
      plt.gca().add_artist(a)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-12
        • 2021-09-11
        • 1970-01-01
        • 1970-01-01
        • 2012-01-24
        • 2011-12-06
        • 2023-03-03
        • 2011-11-17
        相关资源
        最近更新 更多