带注释的水平条形图

时间:2017-03-17 15:12:04

标签: python pandas matplotlib kernel anaconda

我成功运行代码时显然python内核死了,每次运行此代码时都会死掉: 这是代码有问题还是问题更严重?我可以毫无问题地运行其他笔记本。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.rcParams['text.usetex'] = False



df = pd.DataFrame(np.random.uniform(size=37)*100, columns=['A'])

ax = plt.figure(figsize=(10,5))

plt.barh(df.index, df['A'], color='ForestGreen')
plt.yticks(df.index)


def annotateBars(row, ax=ax):
    if row['A'] < 20:
        color = 'black'
        horalign = 'right'
        horpad = 2
    else:
        color = 'white'
        horalign = 'right'
        horpad = -2

    ax.text(row.name, row['A'] + horpad, "{:.1f}%".format(row['A']),
         color=color,
            horizontalalignment=horalign,
            verticalalignment='center',
            fontsize=10)

junk = df.apply(annotateBars, ax=ax, axis=1)

2 个答案:

答案 0 :(得分:3)

也许你应该改变问题的标题,因为对你来说,为什么内核死了并不重要。据我所知,问题是:

使用不同的条形颜色创建水平条形图,并将每个条形的值作为注释。

以下是使用Seaborn的解决方案:

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np 
import pandas 

sns.set(style="darkgrid")
sns.set_color_codes("muted")

# Create example DataFrame
df = pandas.DataFrame(np.random.uniform(size=20)*100, columns=['A']) 

# Create list of colors based on a condition 
colors = ['red' if (x < 20) else 'green' for x in df['A']]

# Create barplot 
ax = sns.barplot(data=df.transpose(), palette=colors, orient='h')
# Annotate every single Bar with its value, based on it's width           
for p in ax.patches:
    width = p.get_width()
    plt.text(5+p.get_width(), p.get_y()+0.55*p.get_height(),
             '{:1.2f}'.format(width),
             ha='center', va='center')

创建:

enter image description here

更新: 为了着色文本:

for p in ax.patches:
    width = p.get_width()
    if width < 20:
        clr = 'red'
    else:
        clr = 'green'
    plt.text(5+p.get_width(), p.get_y()+0.55*p.get_height(),
             '{:1.2f}'.format(width),color=clr,
             ha='center', va='center')

使图更大,背景也包括注释:

ax.set_xlim([0, max(df['A'])+10])

答案 1 :(得分:0)

太好了!我可以在水平条形图上写注释。 好吧,如果我有多个酒吧,该怎么办? seaborn horizontal barplot with annotation

经过多次尝试后,我的代码起作用:

cnt=0
for p in ax.patches:
    width=p.get_width()
    if cnt%2==0:
        a=p.get_width()-5
        clr = 'purple'
    else:
        a=p.get_width()+5
        clr = 'blue'
    plt.text(a, 
    p.get_y()+0.55*p.get_height(),'{:1.2f}'.format(width),color=clr,ha='center', va='center')
    cnt=cnt+1

结果是:

annotated horizontal barplot