在python的方框图中显示均值? [英] Show mean in the box plot in python?

查看:638
本文介绍了在python的方框图中显示均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Matplotlib, and as I am learning how to draw box plot in python, I was wondering if there is a way to show mean in the box plots? Below is my code..

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标志,它也会出现以下错误.

Even though I have showmean flag on, it gives me the following error.

TypeError: boxplot() got an unexpected keyword argument 'showmeans'

推荐答案

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

This is a minimal example and produces the desired result:

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版实现相同的功能,则必须手动绘制均值.这是如何执行此操作的示例:

If you want to achieve the same with matplotlib version 1.3.1 you'll have to plot the means manually. This is an example of how to do it:

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()

结果:

这篇关于在python的方框图中显示均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆