【问题标题】:How to create a swarm plot with matplotlib如何使用 matplotlib 创建群图
【发布时间】:2016-03-22 11:40:10
【问题描述】:

我知道这个问题信息量不大..但由于我不知道他的情节类型的名称,我无法提供更多信息..

[EDIT] 我改了标题,现在信息量更大了……

【问题讨论】:

标签: matplotlib swarmplot


【解决方案1】:

您可以使用seaborn.swarmplot 执行类似的操作。我还使用seaborn.boxplot(关闭了胡须和帽子)来绘制平均值和范围:

import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
ax = sns.swarmplot(x="day", y="total_bill", data=tips)
ax = sns.boxplot(x="day", y="total_bill", data=tips,
        showcaps=False,boxprops={'facecolor':'None'},
        showfliers=False,whiskerprops={'linewidth':0})

plt.show()

【讨论】:

    【解决方案2】:

    如果(无论出于何种原因)您不想使用 seaborn,您可以自己制作它们(例如,请参阅此解释:https://www.flerlagetwins.com/2020/11/beeswarm.html)。

    一个简单的版本是:

    #!/usr/bin/env python3
    import matplotlib.pyplot as plt
    import numpy as np
    
    
    def simple_beeswarm(y, nbins=None):
        """
        Returns x coordinates for the points in ``y``, so that plotting ``x`` and
        ``y`` results in a bee swarm plot.
        """
        y = np.asarray(y)
        if nbins is None:
            nbins = len(y) // 6
    
        # Get upper bounds of bins
        x = np.zeros(len(y))
        ylo = np.min(y)
        yhi = np.max(y)
        dy = (yhi - ylo) / nbins
        ybins = np.linspace(ylo + dy, yhi - dy, nbins - 1)
    
        # Divide indices into bins
        i = np.arange(len(y))
        ibs = [0] * nbins
        ybs = [0] * nbins
        nmax = 0
        for j, ybin in enumerate(ybins):
            f = y <= ybin
            ibs[j], ybs[j] = i[f], y[f]
            nmax = max(nmax, len(ibs[j]))
            f = ~f
            i, y = i[f], y[f]
        ibs[-1], ybs[-1] = i, y
        nmax = max(nmax, len(ibs[-1]))
    
        # Assign x indices
        dx = 1 / (nmax // 2)
        for i, y in zip(ibs, ybs):
            if len(i) > 1:
                j = len(i) % 2
                i = i[np.argsort(y)]
                a = i[j::2]
                b = i[j+1::2]
                x[a] = np.arange(1, 1 + len(a)) * dx
                x[b] = np.arange(1, 1 + len(b)) * -dx
    
        return x
    
    
    fig = plt.figure(figsize=(2, 4))
    fig.subplots_adjust(0.2, 0.1, 0.98, 0.99)
    ax = fig.add_subplot(1, 1, 1)
    y = np.random.gamma(20, 10, 100)
    x = simple_beeswarm(y)
    ax.plot(x, y, 'o')
    fig.savefig('bee.png')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-20
      • 2023-03-14
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 2021-12-13
      相关资源
      最近更新 更多