Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to display text on Boxplot in Python?
A boxplot (also known as box-and-whisker plot) is a graphical representation that displays the median, quartiles, and outliers of a dataset. The box represents the interquartile range (IQR), with the median shown as a line within the box. Whiskers extend to show the data range, while outliers appear as individual points.
You can add text annotations to boxplots using matplotlib.pyplot.text() to label features, highlight outliers, or provide contextual information.
Syntax
To display text on a boxplot in Python, use the following syntax ?
matplotlib.pyplot.text(x, y, text, **kwargs)
The text() function takes three main parameters:
- x, y ? Coordinates where the text will be positioned
- text ? The actual text string to display
- **kwargs ? Optional formatting parameters like fontsize, color, bbox, etc.
Basic Text on Horizontal Boxplot
Here's how to add a simple text label to a horizontal boxplot ?
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
df = pd.DataFrame(np.random.rand(25, 4), columns=['A', 'B', 'C', 'D'])
plt.figure(figsize=(10, 5))
plt.boxplot(df['B'], vert=False)
# Add text with background box
plt.text(0.3, 0.7, 'Boxplot', fontsize=18, fontweight='bold',
bbox={'facecolor': 'lightgreen', 'pad': 10, 'alpha': 0.5})
plt.title('Horizontal Boxplot with Text Annotation')
plt.show()
Styled Text with Custom Colors
You can customize text appearance with colors and transparency ?
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
df = pd.DataFrame(np.random.rand(25, 4), columns=['A', 'B', 'C', 'D'])
plt.figure(figsize=(10, 5))
plt.boxplot(df['A'], vert=False)
# Add styled text
plt.text(0.7, 1.4, 'Column A Distribution', fontsize=18, fontweight='bold',
color='red', alpha=0.8, backgroundcolor='yellow')
plt.title('Boxplot with Colored Text')
plt.show()
Multiple Text Annotations
Add multiple text elements to highlight different parts of the boxplot ?
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Create sample data with some outliers
np.random.seed(42)
data = np.random.normal(50, 15, 100)
data = np.append(data, [10, 90, 95]) # Add outliers
plt.figure(figsize=(10, 6))
box_plot = plt.boxplot(data, vert=True)
# Add multiple text annotations
plt.text(1.1, 50, 'Median', fontsize=12, ha='left',
bbox={'facecolor': 'lightblue', 'pad': 5})
plt.text(1.1, 90, 'Outliers', fontsize=12, ha='left', color='red',
bbox={'facecolor': 'lightyellow', 'pad': 5})
plt.text(0.7, 20, 'Q1-Q3\nRange', fontsize=10, ha='center',
bbox={'facecolor': 'lightgreen', 'pad': 5})
plt.title('Boxplot with Multiple Text Annotations')
plt.ylabel('Values')
plt.show()
Key Text Parameters
| Parameter | Description | Example |
|---|---|---|
fontsize |
Text size | 12, 'large' |
fontweight |
Text weight | 'bold', 'normal' |
color |
Text color | 'red', '#FF0000' |
bbox |
Background box | {'facecolor': 'yellow'} |
ha |
Horizontal alignment | 'left', 'center', 'right' |
Conclusion
Adding text to boxplots enhances visualization by labeling key features, highlighting outliers, or providing context. Use plt.text() with appropriate coordinates and styling parameters to create informative and visually appealing boxplot annotations.
