Matplotlib:非随机抖动

时间:2015-11-27 20:48:09

标签: python r matplotlib scatter-plot jitter

我已阅读问题Matplotlib: avoiding overlapping datapoints in a "scatter/dot/beeswarm" plot和问题Adding a scatter of points to a boxplot using matplotlib但是我想生成使用R生成的图:

R plots http://www.cbs.dtu.dk/~eklund/beeswarm/beeswarm_example_02.png

Here是用于这些数字的代码。

我想用matplotlib来做,但到目前为止我只设法使用np.random.normal(i, 0.05)。这些点彼此分开,但我想订购它们。

This answer做了类似于我想要的事情,但我的数据是浮点数,它们非常接近但不同,因此groupby函数不起作用,我想要与中心对称的点,如上图所示用R生成的图所示。

1 个答案:

答案 0 :(得分:1)

正如此问题Matplotlib: avoiding overlapping datapoints in a "scatter/dot/beeswarm" plot编辑所指出的那样,我在开头没有读到,有一个python包用于那种情节:

https://github.com/mgymrek/pybeeswarm

当然,该软件包比下面的代码做得好得多。

我修改了this answer的代码以接受浮点数,我得到的东西与我想要的略有相似。这是代码:

CA = [0,4,0,3,0,5]  
CB = [0,0,4,4,2,2,2,2,3,0,5] 
CC = [0.08423, 4.0078, 0.02936, 0.04862, 3.2105, 3.7796, 1.9974, 1.6986, 1.7443, 1.6615, 1, 1, 1]

lists = [CA, CB, CC]

x = []
y = []
for index1, my_list in enumerate(lists):
    scores_bins = {}
    for index2, score in enumerate(my_list):
        binx = round(score, 1)
        if binx not in scores_bins:
            scores_bins[binx] = []
        scores_bins[binx].append(score)

    for key, val in sorted(scores_bins.items()):
        values = scores_bins[key]
        points = len(values)
        pos = 1 + index1 + (1 - points) / 50.
        for value in values:
            x.append(pos)
            y.append(value)
            pos += 0.05

plt.plot(x, y, 'o')
plt.xlim((0,4))
plt.ylim((-1,6))

plt.show()

但是,如果pos增加,则点会向右移动,而不是仅从中心向左右传播...