Matplotlib-用值z标记线上的点(x,y) [英] Matplotlib - labelling points (x,y) on a line with a value z

查看:390
本文介绍了Matplotlib-用值z标记线上的点(x,y)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用pyplot制作2d图.我正在读取一个包含几列的文件,每列包含1到10之间的大约100个值.我正在对第6列绘制第5列,这很好.

I'm trying to make a 2d plot using pyplot. I'm reading in a file with several columns, each of which contains around 100 values between 1 and 10. I'm plotting column 5 against column 6, which is fine.

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

What I also want to do is label the resulting line with integer values from column 0. So the line will have 11 points on, at the positions (x,y) where column 0 is an integer. I'd also like those points to be labelled with that integer.

我非常感谢您提供的任何帮助,这使我发疯!

I'd really appreciate any help with this, its driving me crazy!

推荐答案

从您的问题中,我不是100%确切地知道您想要做什么.

From your question, I'm not 100% clear exactly what you're wanting to do.

您是否只想标记一行中的每个顶点?还是只想标记整数的顶点?还是您想在整数交点"沿线插入并标记这些点的地方进行插值?

Do you just want to label every vertex in a line? Or do you only want to label vertices that are integers? Or do you want to interpolate where integer "crossings" would line along the line and label those?

首先,要加载文本文件,请查看numpy.loadtxt(如果尚未加载).在您的特定情况下,您可以执行以下操作:

First off, for loading your text file, look into numpy.loadtxt, if you aren't already. In your particular case, you could do something like:

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

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

At any rate, as a quick example of the simplest option (labeling every vertex):

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()

现在,对于第二种选择,我们可能会有更多类似这样的内容(类似于@ mathematical.coffee的建议):

Now, for the second option, we might have something more like this (Similar to what @mathematical.coffee suggested):

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()

这篇关于Matplotlib-用值z标记线上的点(x,y)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆