簡體   English   中英

將數據標簽添加到Seaborn因子圖

[英]Add data labels to Seaborn factor plot

我想為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')

此圖像已創建

如何將“計數”值添加到圖表上每個條形的頂部?

你可以這樣做:

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()

圖片

來自@ nickil-maveli的上述答案簡直太棒了。 這只是為了在將數據標簽添加到條形圖時添加一些關於參數的清晰度(正如@ user27074在評論中所要求的那樣)

 # loop through all bars of the barplot
for nr, p in enumerate(ax.patches):

    # height of bar, which is basically the data value
    height = p.get_height() 

    # add text to specified position
    ax.text(
        # bar to which data label will be added 
        # so this is the x-coordinate of the data label
        nr, 

        # height of data label: height / 2. is in the middle of the bar
        # so this is the y-coordinate of the data label
        height / 2., 

        # formatting of data label
        u'{:0.1f}%'.format(height), 

        # color of data label
        color='black', 

        # size of data label
        fontsize=18, 

        # horizontal alignment: possible values are center, right, left
        ha='center', 

        # vertical alignment: possible values are top, bottom, center, baseline
        va='center'
    )

你可以做一些更簡單的事情

plt.figure(figsize=(4, 3))
plot = sns.catplot(x='Sex', y='count', kind='bar', data=titanic_df)

# plot.ax gives the axis object
# plot.ax.patches gives list of bars that can be access using index starting at 0

for i, bar in enumerate(plot.ax.patches):
    h = bar.get_height()
    plot.ax.text(
        i, # bar index (x coordinate of text)
        h+10, # y coordinate of text
        '{}'.format(int(h)),  # y label
        ha='center', 
        va='center', 
        fontweight='bold', 
        size=14)

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM