代码之家  ›  专栏  ›  技术社区  ›  veg2020

在Seaborn的方框图中显示平均值[副本]

  •  0
  • veg2020  · 技术社区  · 7 年前

    我是matplotlib的新手,在学习如何用python绘制box plot时,我想知道是否有方法显示mean in the box plots? 下面是我的代码…

    from pylab import *
    import matplotlib.pyplot as plt
    data1=np.random.rand(100,1)
    data2=np.random.rand(100,1)
    data_to_plot=[data1,data2]
    #Create a figure instance
    fig = plt.figure(1, figsize=(9, 6))
    # Create an axes instance
    axes = fig.add_subplot(111)    
    # Create the boxplot
    bp = axes.boxplot(data_to_plot,**showmeans=True**)
    

    即使我打开了showmean标志,它也会给我以下错误。

    TypeError: boxplot() got an unexpected keyword argument 'showmeans'
    
    0 回复  |  直到 11 年前
        1
  •  23
  •   hitzg    11 年前

    这是一个最小的示例,并产生所需的结果:

    import matplotlib.pyplot as plt
    import numpy as np
    
    data_to_plot = np.random.rand(100,5)
    
    fig = plt.figure(1, figsize=(9, 6))
    ax = fig.add_subplot(111)    
    bp = ax.boxplot(data_to_plot, showmeans=True)
    
    plt.show()
    

    编辑:

    如果你想在matplotlib版本1.3.1中达到同样的效果,你必须手动绘制平均值。这是一个如何做到的例子:

    import matplotlib.pyplot as plt
    import numpy as np
    
    data_to_plot = np.random.rand(100,5)
    positions = np.arange(5) + 1
    
    fig, ax = plt.subplots(1,2, figsize=(9,4))
    
    # matplotlib > 1.4
    bp = ax[0].boxplot(data_to_plot, positions=positions, showmeans=True)
    ax[0].set_title("Using showmeans")
    
    #matpltolib < 1.4
    bp = ax[1].boxplot(data_to_plot, positions=positions)
    means = [np.mean(data) for data in data_to_plot.T]
    ax[1].plot(positions, means, 'rs')
    ax[1].set_title("Plotting means manually")
    
    plt.show()
    

    结果:

    enter image description here

        2
  •  3
  •   NargesooTv    10 年前

    您还可以升级matplotlib:

     pip2 install matplotlib --upgrade
    

    然后

    bp = axes.boxplot(data_to_plot,showmeans=True)