【问题标题】:Label python data points on plot在绘图上标记 python 数据点
【发布时间】:2014-03-08 16:41:19
【问题描述】:

我搜索了年龄(小时,就像年龄一样)来找到一个非常烦人(看似基本的)问题的答案,并且因为我找不到一个完全符合答案的问题,所以我发布了一个问题并在希望它可以节省其他人我刚刚花在我的新手绘图技能上的大量时间。

如果你想使用 python matplotlib 标记你的绘图点

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = anyarray
B = anyotherarray

plt.plot(A,B)
for i,j in zip(A,B):
    ax.annotate('%s)' %j, xy=(i,j), xytext=(30,0), textcoords='offset points')
    ax.annotate('(%s,' %i, xy=(i,j))

plt.grid()
plt.show()

我知道 xytext=(30,0) 与文本坐标一起使用,您使用这 30,0 值来定位数据标签点,因此它位于 0 y 轴上,30 位于 x 轴上小面积。

你需要绘制 i 和 j 的线,否则你只绘制 x 或 y 数据标签。

你会得到这样的东西(只注意标签):

它并不理想,仍有一些重叠 - 但总比没有好,这就是我所拥有的......

【问题讨论】:

  • 为什么不直接做ax.annotate('(%s, %s)' % (i, j), ...)? (或者,如果您使用的是较新的字符串格式,'({}, {})'.format(i, j)。)
  • pyplot.text 似乎是注释的替代品:pythonmembers.club/2018/05/08/… 不确定它是否有任何不同
  • pythonmembers.club 的维护者在这里。 XD 这就是我作为初学者的原因。那篇文章后来变得足够受欢迎,被纳入斯坦福大学的 NLP 课程(哇,这篇文章的粗体直接链接)

标签: python matplotlib labels annotate


【解决方案1】:

如何一次打印(x, y)

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

ax.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

ax.grid()
plt.show()

【讨论】:

  • 对于任何使用此功能的人来说,请注意:textcoords='offset points' 似乎会根据图表的比例产生不同的效果(对我来说,这导致大多数标签出现在情节)
  • 是的,您应该改用 textcoords='data'。
  • @navari,感谢您提供的信息。我相应地更新了答案。
  • @EricG - 我相信textcoords='offset points' 也需要xytext 参数。换句话说,将xytext=(x points, y points) 设置为偏移量,textcoords='offset points' 将按预期工作。
【解决方案2】:

我遇到了类似的问题,结果是这样的:

对我来说,这样做的好处是数据和注释不重叠。

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

.annotate 中使用文本参数会导致文本位置不利。 在图例和数据点之间画线是一团糟,因为图例的位置很难确定。

【讨论】:

    猜你喜欢
    • 2020-07-10
    • 2017-02-13
    • 1970-01-01
    • 2017-05-12
    • 2021-12-01
    • 2021-06-21
    • 2019-04-26
    • 2021-09-04
    • 2019-05-07
    相关资源
    最近更新 更多