How to show mean in a box plot in Python Matploblib?

To show the mean in a box plot using Matplotlib, we can use the showmeans=True parameter in the boxplot() method. This displays the mean as a marker (typically a triangle) on each box.

Basic Box Plot with Mean

Let's create a simple box plot that displays the mean for each dataset ?

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
data = np.random.rand(100, 3)

# Create box plot with mean displayed
plt.figure(figsize=(8, 6))
bp = plt.boxplot(data, showmeans=True)

plt.title('Box Plot with Mean Values')
plt.xlabel('Dataset')
plt.ylabel('Values')
plt.show()

Customizing Mean Markers

You can customize the appearance of the mean markers using meanprops parameter ?

import matplotlib.pyplot as plt
import numpy as np

# Create sample data with different distributions
np.random.seed(42)
data1 = np.random.normal(50, 15, 100)
data2 = np.random.normal(60, 10, 100)
data3 = np.random.normal(45, 20, 100)

data = [data1, data2, data3]

# Create box plot with customized mean markers
plt.figure(figsize=(10, 6))
bp = plt.boxplot(data, 
                showmeans=True,
                meanprops={'marker': 'o', 'markerfacecolor': 'red', 
                          'markeredgecolor': 'black', 'markersize': 8})

plt.title('Box Plot with Custom Mean Markers')
plt.xlabel('Groups')
plt.ylabel('Values')
plt.xticks([1, 2, 3], ['Group A', 'Group B', 'Group C'])
plt.grid(True, alpha=0.3)
plt.show()

Box Plot with Mean Line

You can also display a line connecting the means using showmeans=True and meanline=True ?

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
np.random.seed(123)
data = [np.random.normal(0, std, 100) for std in range(1, 5)]

# Create box plot with mean line
plt.figure(figsize=(10, 6))
bp = plt.boxplot(data, 
                showmeans=True,
                meanline=True,
                meanprops={'color': 'red', 'linewidth': 2})

plt.title('Box Plot with Mean Line')
plt.xlabel('Dataset')
plt.ylabel('Values')
plt.show()

Parameters Summary

Parameter Description Default
showmeans Show/hide mean markers False
meanline Display mean as line instead of marker False
meanprops Dictionary of mean marker/line properties Default styling

Conclusion

Use showmeans=True to display mean values in box plots. Customize the appearance with meanprops or use meanline=True to show means as lines instead of markers.

Updated on: 2026-03-25T21:47:50+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements