Matplotlib - 在值为z的线上标记点(x,y)

use*_*963 7 python label matplotlib

我正在尝试用pyplot制作一个2D图.我正在读一个包含多个列的文件,每个列包含大约100个介于1和10之间的值.我正在将第5列绘制在第6列,这很好.

我还想做的是用第0列的整数值标记结果行.因此该行将在位置(x,y)上有11个点,其中第0列是整数.我也希望这些点用该整数标记.

我真的很感激任何帮助,它让我疯狂!

Joe*_*ton 26

从你的问题来看,我并不是100%清楚你想要做什么.

你只想标记一行中的每个顶点吗?或者你只想标记整数的顶点?或者你想插入整数"交叉"沿着直线排列的位置并标记它们?

首先numpy.loadtxt,如果您还没有加载文本文件,请查看.在您的特定情况下,您可以执行以下操作:

z, x, y = np.loadtxt('data.txt', usecols=[0, 5, 6]).T
Run Code Online (Sandbox Code Playgroud)

无论如何,作为最简单选项(标记每个顶点)的快速示例:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = 2 * x
z = x ** 2

fig, ax = plt.subplots()
ax.plot(x, y, 'bo-')

for X, Y, Z in zip(x, y, z):
    # Annotate the points 5 _points_ above and to the left of the vertex
    ax.annotate('{}'.format(Z), xy=(X,Y), xytext=(-5, 5), ha='right',
                textcoords='offset points')

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在,对于第二个选项,我们可能会有更像这样的东西(与@ mathematical.coffee建议的类似):

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-0.6, 5.6, 0.2)
y = 2 * x
z = x**2

fig, ax = plt.subplots()
ax.plot(x, y, 'bo-')

# Note the threshold... I'm assuming you want 1.000001 to be considered an int.
# Otherwise, you'd use "z % 1 == 0", but beware exact float comparisons!!
integers = z % 1 < 1e-6
for (X, Y, Z) in zip(x[integers], y[integers], z[integers]):
    ax.annotate('{:.0f}'.format(Z), xy=(X,Y), xytext=(-10, 10), ha='right',
                textcoords='offset points', 
                arrowprops=dict(arrowstyle='->', shrinkA=0))

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述