Show average on chart in python?

I am new to Matplotlib, and when I learn how to draw a field in python, I was wondering if there is a way to show the average value in field charts? 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 if I have a showmean flag, it gives me the following error.

TypeError: boxplot() got an unexpected keyword argument 'showmeans'
+4
source share
2 answers

This is a minimal example and gives 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 will have to draw the tools manually. This is an example of how to do this:

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:

enter image description here

+12
source

You can also update matplotlib:

 pip2 install matplotlib --upgrade

and then

bp = axes.boxplot(data_to_plot,showmeans=True)
+2
source

Source: https://habr.com/ru/post/1583816/


All Articles