在python的箱线图中显示平均值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29777017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show mean in the box plot in python?
提问by parth patel
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..
我是 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**)
Even though I have showmean flag on, it gives me the following error.
即使我打开了 showmean 标志,它也会给我以下错误。
TypeError: boxplot() got an unexpected keyword argument 'showmeans'
采纳答案by hitzg
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:
如果您想使用 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()
Result:
结果:
回答by NargesooTv
You could also upgrade the matplotlib:
您还可以升级 matplotlib:
pip2 install matplotlib --upgrade
and then
进而
bp = axes.boxplot(data_to_plot,showmeans=True)