2016-09-12 85 views
2

我想將數據標籤添加到由Seaborn生成的因子圖。這裏有一個例子:將數據標籤添加到Seaborn因子圖

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

我怎樣才能將「計數」值添加到圖表上的每欄的頂部?

回答

5

你可以這樣來做:

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