在python的框图中显示平均值?

时间:2015-04-21 15:40:05

标签: python boxplot matplotlib

我是Matplotlib的新手,当我学习如何在python中绘制方块图时,我想知道是否有办法在方块图中显示平均值? 以下是我的代码..

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'

2 个答案:

答案 0 :(得分:19)

这是一个最小的例子,可以产生所需的结果:

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

答案 1 :(得分:3)

你也可以升级matplotlib:

 pip2 install matplotlib --upgrade

然后

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