在 python 的箱形图中显示均值?
Show mean in the box plot in python?
我是 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'
这是一个最小的示例,并产生了预期的结果:
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()
结果:
您还可以升级 matplotlib:
pip2 install matplotlib --upgrade
然后
bp = axes.boxplot(data_to_plot,showmeans=True)
我是 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'
这是一个最小的示例,并产生了预期的结果:
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()
结果:
您还可以升级 matplotlib:
pip2 install matplotlib --upgrade
然后
bp = axes.boxplot(data_to_plot,showmeans=True)