在matplotlib中绘制数据点计数

1 投票
1 回答
1183 浏览
提问于 2025-04-17 23:05

我有一个用 matplotlib 制作的散点图,像下面这样。

import matplotlib.pyplot as plt
from pylab import plot,axis,show,pcolor,colorbar,bone

axiss = [(0, 0), (0, 1), (0, 0), (2, 2), (0, 2), (2, 2), (2, 0), (0, 2), (1, 2), (2, 0)]
x,y = zip(*axiss)


labels = ['u1', 'u2', 'u3', 'u4',
         'u5', 'u6', 'u7', 'u8',
         'u9', 'u10']

fig, ax = plt.subplots()
ax.scatter(x, y)
for i, txt in enumerate(labels):
    ax.annotate(txt, (x[i],y[i]))
show()

我想要在图上显示每个点上有多少个数据点,而不是显示标签。比如在我用红色标记的数据点上,它应该显示'2'。而当我把鼠标放上去时,需要看到标签。所以在这个例子中,它应该显示'u7'和'u10'。请问用 matplotlib 可以做到吗?

enter image description here

1 个回答

2

这段内容有点长,但我会先用 set 来收集 axiss 中的独特元素,并计算每个独特元素的数量。然后把这些数据放进 scatter 的第三个参数,也就是点的大小。我还会根据每个点的数据集数量来给每个点添加注释。

现在,互动注释是个比较棘手的部分。我找不到鼠标悬停事件的捕捉方法,但你可以用鼠标点击事件来实现类似的效果。把这个页面上的第一个脚本 http://wiki.scipy.org/Cookbook/Matplotlib/Interactive_Plotting 保存为 interactive_annotations.py,然后在你的脚本中导入它。

import matplotlib.pyplot as plt
from pylab import plot,axis,show,pcolor,colorbar,bone
import numpy as np

axiss = [(0, 0), (0, 1), (0, 0), (2, 2), (0, 2), (2, 2), (2, 0), (0, 2), (1, 2), (2, 0)]

# get unique elements
axiss_unique = list(set(axiss))
# get number of data at each datapoint
axiss_count = [axiss.count(x) for x in axiss_unique]

sc = 100 # scale up the datapoints for scatter
labels = [] # label each point according to number of data there
annotates = [] # intereactively label each point according to the datapoint name
for i in range(len(axiss_count)):
    labels.append('%i'%axiss_count[i])
    annotates.append( ' '.join(['u'+str(k) for k, j in enumerate(axiss) if j == axiss_unique[i]]))
    axiss_count[i] *= sc

x,y = zip(*axiss_unique)

fig, ax = plt.subplots()
# get offsets of the labels to each point
x_os, y_os = max(x)/20., max(y)/20.
ax.scatter(x, y, axiss_count)
for i, txt in enumerate(labels):
    ax.annotate(txt, (x[i]+x_os,y[i]+y_os), fontsize=15)

# interactive annotation
import interactive_annotations

af =  interactive_annotations.AnnoteFinder(x,y, annotates)
connect('button_press_event', af)

show()

结果大概是这样的。

enter image description here

你可以编辑 interactive_annotations.py 来改变注释的偏移量、字体等等。

撰写回答