带批注的水平条形图

2024-10-01 09:29:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在成功运行代码,显然每次运行此代码时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)

Tags: 代码textimportdfindexmatplotlibasnp
2条回答
太好了!我可以在水平条形图上写注释。 好吧,如果我有多个酒吧怎么办? 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

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

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

下面是一个使用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

更新: 也可为文本着色:

^{pr2}$

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

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

相关问题 更多 >