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

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

EDIT:

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

Result:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值