Matplotlib:避免在"散点/点/ beeswarm"图中重叠数据点

iay*_*ork 38 python charts matplotlib

使用matplotlib绘制点图时,我想偏移重叠的数据点以使它们全部可见.例如,如果我有

CategoryA: 0,0,3,0,5  
CategoryB: 5,10,5,5,10  
Run Code Online (Sandbox Code Playgroud)

我希望每个CategoryA"0"数据点并排设置,而不是彼此重叠,同时仍然保持不同CategoryB.

在R(ggplot2)中有一个"jitter"选项可以做到这一点.在matplotlib中是否有类似的选项,还是有另一种方法可以导致类似的结果?

编辑:为了澄清, R中"beeswarm"情节基本上是我的想法,并且pybeeswarm是matplotlib/Python版本的早期但有用的开始.

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

yoa*_*ram 36

通过@ 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)
Run Code Online (Sandbox Code Playgroud)

stdev变量确保抖动足以在不同的尺度上看到,但它假设轴的极限是0和最大值.

然后你可以打电话jitter而不是scatter.


sun*_*iyu 9

我使用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()
Run Code Online (Sandbox Code Playgroud)

X分散数据


joe*_*lom 9

Seaborn通过以下方式提供类似直方图的分类点图,sns.swarmplot()并通过以下方式提供抖动的分类点图sns.stripplot()

import seaborn as sns

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

sns.swarmplot('species', 'sepal_length', data=iris)
sns.despine()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

sns.stripplot('species', 'sepal_length', data=iris, jitter=0.2)
sns.despine()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


ali*_*i_m 8

解决问题的一种方法是将散点图/点/贝索瓦图中的每个"行"视为直方图中的bin:

data = np.random.randn(100)

width = 0.8     # the maximum width of each 'row' in the scatter plot
xpos = 0        # the centre position of the scatter plot in x

counts, edges = np.histogram(data, bins=20)

centres = (edges[:-1] + edges[1:]) / 2.
yvals = centres.repeat(counts)

max_offset = width / counts.max()
offsets = np.hstack((np.arange(cc) - 0.5 * (cc - 1)) for cc in counts)
xvals = xpos + (offsets * max_offset)

fig, ax = plt.subplots(1, 1)
ax.scatter(xvals, yvals, s=30, c='b')
Run Code Online (Sandbox Code Playgroud)

这显然涉及对数据进行分箱,因此您可能会失去一些精确度.如果您有离散数据,则可以替换:

counts, edges = np.histogram(data, bins=20)
centres = (edges[:-1] + edges[1:]) / 2.
Run Code Online (Sandbox Code Playgroud)

有:

centres, counts = np.unique(data, return_counts=True)
Run Code Online (Sandbox Code Playgroud)

即使对于连续数据,保留精确y坐标的另一种方法是使用核密度估计来缩放x轴中随机抖动的幅度:

from scipy.stats import gaussian_kde

kde = gaussian_kde(data)
density = kde(data)     # estimate the local density at each datapoint

# generate some random jitter between 0 and 1
jitter = np.random.rand(*data.shape) - 0.5 

# scale the jitter by the KDE estimate and add it to the centre x-coordinate
xvals = 1 + (density * jitter * width * 2)

ax.scatter(xvals, data, s=30, c='g')
for sp in ['top', 'bottom', 'right']:
    ax.spines[sp].set_visible(False)
ax.tick_params(top=False, bottom=False, right=False)

ax.set_xticks([0, 1])
ax.set_xticklabels(['Histogram', 'KDE'], fontsize='x-large')
fig.tight_layout()
Run Code Online (Sandbox Code Playgroud)

第二种方法基于小提琴图的工作方式.它仍然不能保证没有一个点重叠,但我发现在实践中,只要有一个相当数量的点(> 20),它往往会给出相当漂亮的结果,并且分布可以合理地近似由高斯总和.

在此输入图像描述


joa*_*uin 7

在这里不知道直接的mpl替代方案,你有一个非常基本的建议:

from matplotlib import pyplot as plt
from itertools import groupby

CA = [0,4,0,3,0,5]  
CB = [0,0,4,4,2,2,2,2,3,0,5]  

x = []
y = []
for indx, klass in enumerate([CA, CB]):
    klass = groupby(sorted(klass))
    for item, objt in klass:
        objt = list(objt)
        points = len(objt)
        pos = 1 + indx + (1 - points) / 50.
        for item in objt:
            x.append(pos)
            y.append(item)
            pos += 0.04

plt.plot(x, y, 'o')
plt.xlim((0,3))

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

在此输入图像描述


wor*_*ise 6

Seaborn 的 swarmplot 似乎最适合您的想法,但您也可以使用 Seaborn 的 regplot 进行调整:

import seaborn as sns
iris = sns.load_dataset('iris')

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

sns.regplot(x='sepal_length',
            y='sepal_width',
            data=iris,
            fit_reg=False,  # do not fit a regression line
            x_jitter=0.1,  # could also dynamically set this with range of data
            y_jitter=0.1,
            scatter_kws={'alpha': 0.5})  # set transparency to 50%
Run Code Online (Sandbox Code Playgroud)


小智 5

通过@wordsforthewise扩展答案(抱歉,不能用我的声誉发表评论),如果您需要抖动和使用色调来按某些分类对点进行着色(就像我所做的那样),Seaborn 的 lmplot 是一个不错的选择,而不是 reglpot :

import seaborn as sns
iris = sns.load_dataset('iris')
sns.lmplot(x='sepal_length', y='sepal_width', hue='species', data=iris, fit_reg=False, x_jitter=0.1, y_jitter=0.1)  
Run Code Online (Sandbox Code Playgroud)