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 get data labels on a Seaborn pointplot?
To get data labels on a Seaborn pointplot, you need to access the plotted points and add annotations manually using matplotlib's annotate() function. This technique helps display exact values on each data point for better visualization.
Steps
Set the figure size and adjust the padding between and around the subplots.
Create a DataFrame with sample data for visualization.
Create a pointplot using Seaborn.
Iterate through the plot points and add data labels using annotations.
Display the figure using
show()method.
Example
Here's how to add data labels to a Seaborn pointplot ?
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create sample data
df = pd.DataFrame({'category': ['A', 'B', 'C', 'A', 'B', 'C'],
'values': [10, 15, 12, 8, 18, 14]})
# Create pointplot
ax = sns.pointplot(data=df, x='category', y='values', estimator='mean')
# Add data labels
for i, point in enumerate(ax.collections[0].get_offsets()):
value = point[1] # y-coordinate (the mean value)
ax.annotate(f'{value:.1f}',
(point[0], point[1]),
textcoords="offset points",
xytext=(0,10),
ha='center')
plt.title('Pointplot with Data Labels')
plt.show()
Alternative Method with Value Counts
For displaying frequency counts as labels ?
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create sample data with repeated values
data = pd.DataFrame({'values': [1, 3, 1, 2, 3, 1, 2, 3]})
# Count occurrences
value_counts = data['values'].value_counts().sort_index()
# Create pointplot
ax = sns.pointplot(x=value_counts.index, y=value_counts.values)
# Add count labels
for i, (x, y) in enumerate(zip(value_counts.index, value_counts.values)):
ax.annotate(str(y), (i, y), textcoords="offset points",
xytext=(0,5), ha='center')
plt.xlabel('Values')
plt.ylabel('Count')
plt.title('Value Counts with Labels')
plt.show()
Key Points
ax.collections[0].get_offsets()retrieves the coordinates of plotted pointstextcoords="offset points"positions labels relative to data pointsxytext=(0,10)offsets labels 10 points above the data pointsha='center'centers the text horizontally over each point
Conclusion
Adding data labels to Seaborn pointplots requires manual annotation using matplotlib functions. Use get_offsets() to access point coordinates and annotate() to display values above each point for better data interpretation.
