在图上标记数据点

21 浏览
0 Comments

在图上标记数据点

如果你想使用Python的matplotlib库给图表中的数据点加标签,你可以使用以下代码:

from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
A = 任意数组A
B = 任意其他数组B
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`一起使用,你可以使用这些值来定位数据标签点,使其位于自己的小区域上的`y=0`和`x=30`。

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

你会得到类似于下面这样的结果(注意只有标签):

![我的带有数据点标签的图表](https://i.stack.imgur.com/6jr6C.png)

这还不是理想的,仍然存在一些重叠。

0