Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add data labels to Seaborn factor plot

I would like to add data labels to factor plots generated by Seaborn. Here is an example:

import pandas as pd
from pandas import Series, DataFrame
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

titanic_df = pd.read_csv('train.csv')
sns.factorplot('Sex',data=titanic_df,kind='count')

This image is created

How can I add the 'count' values to the top of each bar on the graph?

like image 768
sparrow Avatar asked Sep 12 '16 06:09

sparrow


People also ask

What is Factorplot in seaborn?

Factor Plot is used to draw a different types of categorical plot . The default plot that is shown is a point plot, but we can plot other seaborn categorical plots by using of kind parameter, like box plots, violin plots, bar plots, or strip plots.

What are patches in seaborn?

The positional parameters (x and y) determining the position (just outside the bar) at which we should print this label. Every bar (and its corresponding background area) is known as a patch within the bar chart object.


1 Answers

You could do it this way:

import math
# Set plotting style
sns.set_style('whitegrid')

# Rounding the integer to the next hundredth value plus an offset of 100
def roundup(x):
    return 100 + int(math.ceil(x / 100.0)) * 100 

df = pd.read_csv('train.csv')
sns.factorplot('Sex', data=df, kind='count', alpha=0.7, size=4, aspect=1)

# Get current axis on current figure
ax = plt.gca()

# ylim max value to be set
y_max = df['Sex'].value_counts().max() 
ax.set_ylim([0, roundup(y_max)])

# Iterate through the list of axes' patches
for p in ax.patches:
    ax.text(p.get_x() + p.get_width()/2., p.get_height(), '%d' % int(p.get_height()), 
            fontsize=12, color='red', ha='center', va='bottom')

plt.show()

Image

like image 59
Nickil Maveli Avatar answered Sep 20 '22 20:09

Nickil Maveli