带注释的水平条形图

Ale*_*x T 2 python kernel matplotlib pandas 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)
Run Code Online (Sandbox Code Playgroud)

sch*_*ump 7

也许您应该更改问题的标题,因为对您而言,内核为何死亡并不重要。据我了解,问题是:

创建具有不同条形颜色和每个条形值作为注释的水平条形图。

这是使用 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')
Run Code Online (Sandbox Code Playgroud)

创建:

在此处输入图片说明

更新:还为文本着色:

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')
Run Code Online (Sandbox Code Playgroud)

使绘图更大,以便背景也覆盖注释:

ax.set_xlim([0, max(df['A'])+10])
Run Code Online (Sandbox Code Playgroud)