简体   繁体   English

带注释的水平条形图

[英]Horizontal barplot with annotations

I was successfully running the code when apparently python kernel died and dies everytime I am running this code: Is it something wrong with the code or the problem is deeper? 我显然在每次运行此代码时都死于python内核而死的时候,我已经成功运行了该代码:代码有问题还是问题更深? I can run other notebooks without problems. 我可以毫无问题地运行其他笔记本。

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)

Maybe you should change the title of the question, because as for you it does not really matter why the Kernel dies. 也许您应该更改问题的标题,因为对于您而言,内核死亡的原因并不重要。 As far as I've understood you, the problem is: 据您了解,问题是:

Creating a horizontal bar chart with different bar colors and the values of each bar as an annotation. 创建具有不同条形颜色的水平条形图,并将每个条形的值作为注释。

Here is a solution using Seaborn: 这是使用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')

Creates: 创建:

在此处输入图片说明

Update: For also coloring the text: 更新:为了给文本加上颜色:

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

Making the plot larger so the background also covers the annotations: 使图更大,以便背景还覆盖注释:

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

Great! 大! I can write annotations on horizontal barplot. 我可以在水平条形图上写注释。 Well, what can i do if i have more than one bars? 好吧,如果我有多个酒吧,该怎么办? seaborn horizontal barplot with annotation 带注释的seaborn水平条形图

After many tries that worked on my code: 经过多次尝试对我的代码起作用:

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

result is: 结果是:

带注释的水平条形图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM