使用matplotlib向箱线图添加散点图

yptwkmov  于 2023-08-06  发布在  其他
关注(0)|答案(4)|浏览(103)

我在this article中看到过这个奇妙的箱线图(图2)。


的数据
如您所见,这是一个箱形图,上面叠加了黑点的散点:x索引黑点(以随机顺序),y是感兴趣的变量。我想用Matplotlib做类似的事情,但我不知道从哪里开始。到目前为止,我在网上找到的箱线图并不那么酷,看起来像这样:



matplotlib文档:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot
给箱线图着色的方法:https://github.com/jbmouret/matplotlib_for_papers#colored-boxes

k4emjkb1

k4emjkb11#

您需要的是一种向x轴添加抖动的方法。
下面是here的例子:

bp = titanic.boxplot(column='age', by='pclass', grid=False)
for i in [1,2,3]:
    y = titanic.age[titanic.pclass==i].dropna()
    # Add some random "jitter" to the x-axis
    x = np.random.normal(i, 0.04, size=len(y))
    plot(x, y, 'r.', alpha=0.2)

字符串
x1c 0d1x的数据
引用链接:
向箱线图添加附加信息的一种方法是覆盖实际数据;这通常最适合于小或中等大小的数据系列。当数据密集时,上面使用的几个技巧有助于可视化:
1.降低alpha级别以使点部分透明
1.沿着x轴添加随机“抖动”以避免过冲
代码看起来像这样:

import pylab as P
import numpy as np

# Define data
# Define numBoxes

P.figure()

bp = P.boxplot(data)

for i in range(numBoxes):
    y = data[i]
    x = np.random.normal(1+i, 0.04, size=len(y))
    P.plot(x, y, 'r.', alpha=0.2)

P.show()

v09wglhw

v09wglhw2#

扩展Kyrubas的解决方案,并仅使用matplotlib进行绘图部分(有时我很难用matplotlib格式化pandas图)。

from matplotlib import cm
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# initialize dataframe
n = 200
ngroup = 3
df = pd.DataFrame({'data': np.random.rand(n), 'group': map(np.floor, np.random.rand(n) * ngroup)})

group = 'group'
column = 'data'
grouped = df.groupby(group)

names, vals, xs = [], [] ,[]

for i, (name, subdf) in enumerate(grouped):
    names.append(name)
    vals.append(subdf[column].tolist())
    xs.append(np.random.normal(i+1, 0.04, subdf.shape[0]))

plt.boxplot(vals, labels=names)
ngroup = len(vals)
clevels = np.linspace(0., 1., ngroup)

for x, val, clevel in zip(xs, vals, clevels):
    plt.scatter(x, val, c=cm.prism(clevel), alpha=0.4)

字符串


的数据

wd2eg0qa

wd2eg0qa3#

**再看一下原来的问题(我自己有更多的经验),我认为sns.swarmplotsns.stripplot更准确。

作为一个更简单、可能更新的选项,您可以使用seabornswarmplot选项。

import seaborn as sns
import matplotlib.pyplot as plt

sns.set(style="whitegrid")
tips = sns.load_dataset("tips")

ax = sns.boxplot(x="day", y="total_bill", data=tips, showfliers = False)
ax = sns.swarmplot(x="day", y="total_bill", data=tips, color=".25")

plt.show()

字符串


的数据

inn6fuwd

inn6fuwd4#

通过Kyrubashwang扩展solutions,你也可以定义一个函数scattered_boxplot(并将其作为一个方法添加到plt.Axes),这样你就可以总是使用scattered_boxplot而不是boxplot

fig, ax = plt.subplots(figsize=(5, 6))
ax.scattered_boxplot(x=[np.array([1,2,3]*50),np.array([1.1,2.2,3.3])])

字符串
函数scattered_boxplot只能使用matplotlib定义如下:

import matplotlib.pyplot as plt

import numpy as np
from numbers import Number

def scattered_boxplot(ax, x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None,
                      showfliers="unif",
                      hide_points_within_whiskers=False,
                      boxprops=None, labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_ticks=True, autorange=False, zorder=None, *, data=None):
    if showfliers=="classic":
        classic_fliers=True
    else:
        classic_fliers=False
    ax.boxplot(x, notch=notch, sym=sym, vert=vert, whis=whis, positions=positions, widths=widths, patch_artist=patch_artist, bootstrap=bootstrap, usermedians=usermedians, conf_intervals=conf_intervals, meanline=meanline, showmeans=showmeans, showcaps=showcaps, showbox=showbox,
               showfliers=classic_fliers,
               boxprops=boxprops, labels=labels, flierprops=flierprops, medianprops=medianprops, meanprops=meanprops, capprops=capprops, whiskerprops=whiskerprops, manage_ticks=manage_ticks, autorange=autorange, zorder=zorder,data=data)
    N=len(x)
    datashape_message = ("List of boxplot statistics and `{0}` "
                             "values must have same the length")
    # check position
    if positions is None:
        positions = list(range(1, N + 1))
    elif len(positions) != N:
        raise ValueError(datashape_message.format("positions"))

    positions = np.array(positions)
    if len(positions) > 0 and not isinstance(positions[0], Number):
        raise TypeError("positions should be an iterable of numbers")

    # width
    if widths is None:
        widths = [np.clip(0.15 * np.ptp(positions), 0.15, 0.5)] * N
    elif np.isscalar(widths):
        widths = [widths] * N
    elif len(widths) != N:
        raise ValueError(datashape_message.format("widths"))

    if hide_points_within_whiskers:
        import matplotlib.cbook as cbook
        from matplotlib import rcParams
        if whis is None:
            whis = rcParams['boxplot.whiskers']
        if bootstrap is None:
            bootstrap = rcParams['boxplot.bootstrap']
        bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap,
                                       labels=labels, autorange=autorange)
    for i in range(N):
        if hide_points_within_whiskers:
            xi=bxpstats[i]['fliers']
        else:
            xi=x[i]
        if showfliers=="unif":
            jitter=np.random.uniform(-widths[i]*0.5,widths[i]*0.5,size=np.size(xi))
        elif showfliers=="normal":
            jitter=np.random.normal(loc=0.0, scale=widths[i]*0.1,size=np.size(xi))
        elif showfliers==False or showfliers=="classic":
            return
        else:
            raise NotImplementedError("showfliers='"+str(showfliers)+"' is not implemented. You can choose from 'unif', 'normal', 'classic' and False")

        plt.scatter(positions[i]+jitter,xi,alpha=0.2,marker="o", facecolors='none', edgecolors="k")


并且可以作为一种方法添加到plt。轴通过

setattr(plt.Axes, "scattered_boxplot", scattered_boxplot)


仍然可以访问箱形图的所有选项,并且另外可以选择用于水平抖动的散射分布(例如,showfliers="unif"),并且可以选择是否也应该显示晶须外部的飞行物(例如,hide_points_within_whiskers=False)。
这个解决方案已经很好用了。另一种方法是直接更改matplotlib的源代码,主要是行:https://github.com/matplotlib/matplotlib/blob/9765379ce6e7343070e815afc0988874041b98e2/lib/matplotlib/axes/_axes.py#L4006

相关问题