在p上标记python数据点

2024-04-29 00:29:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如果要使用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)和textcoords一起使用,你用这些30,0值来定位数据标签点,所以它在0 y轴上,在x轴上,在它自己的小区域上。

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

你得到了这样的东西(只注意标签):
My own plot with data points labeled

这并不理想,仍然有一些重叠-但总比什么都没有好,这就是我所拥有的。。


Tags: 数据答案matplotlibfig绘制plt标签ax
2条回答

我也有过类似的问题,结果是:

enter image description here

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

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中使用文本参数的结果是不合适的文本位置。 在图例和数据点之间绘制线是一团混乱,因为图例的位置很难确定。

马上打印(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

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

plt.grid()
plt.show()

enter image description here

相关问题 更多 >