Matplotlib:避免“分散/点/蜂群”p中的重叠数据点

2024-09-23 10:20:30 发布

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

当使用matplotlib绘制点图时,我希望偏移重叠的数据点以使它们都可见。例如,如果我有

CategoryA: 0,0,3,0,5  
CategoryB: 5,10,5,5,10  

我希望每个CategoryA“0”数据点并排设置,而不是放在彼此的正上方,同时仍然与CategoryB保持不同。

在R(ggplot2)中,有一个"jitter"选项可以做到这一点。matplotlib中是否有类似的选项,或者是否有其他方法会导致类似的结果?

编辑:澄清一下,the ^{} plot in R本质上是我所想的,而^{}是matplotlib/Python版本的一个早期但有用的开始。

编辑:添加Seaborn的Swarmplot,在0.7版中引入,是我想要的一个很好的实现。


Tags: the数据方法in版本编辑plotmatplotlib
3条回答

通过@user2467675扩展答案,我是这样做的:

def rand_jitter(arr):
    stdev = .01*(max(arr)-min(arr))
    return arr + np.random.randn(len(arr)) * stdev

def jitter(x, y, s=20, c='b', marker='o', cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, hold=None, **kwargs):
    return scatter(rand_jitter(x), rand_jitter(y), s=s, c=c, marker=marker, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths, verts=verts, hold=hold, **kwargs)

变量stdev确保抖动足以在不同的尺度上看到,但它假定轴的限制为0和最大值。

然后可以调用jitter,而不是scatter

Seaborn通过^{}提供直方图样的分类点图,通过^{}提供抖动的分类点图:

import seaborn as sns

sns.set(style='ticks', context='talk')
iris = sns.load_dataset('iris')

sns.swarmplot('species', 'sepal_length', data=iris)
sns.despine()

enter image description here

sns.stripplot('species', 'sepal_length', data=iris, jitter=0.2)
sns.despine()

enter image description here

我使用numpy.random将数据沿X轴“散布/蜂群”到每个类别的固定点上,然后基本上对每个类别执行pyplot.scatter():

import matplotlib.pyplot as plt
import numpy as np

#random data for category A, B, with B "taller"
yA, yB = np.random.randn(100), 5.0+np.random.randn(1000)

xA, xB = np.random.normal(1, 0.1, len(yA)), 
         np.random.normal(3, 0.1, len(yB))

plt.scatter(xA, yA)
plt.scatter(xB, yB)
plt.show()

X-scattered data

相关问题 更多 >