gpt4 book ai didi

python - 带注释的水平条形图

转载 作者:行者123 更新时间:2023-12-05 08:56:03 24 4
gpt4 key购买 nike

当我每次运行这段代码时,显然 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)

最佳答案

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

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

这是一个使用 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])

关于python - 带注释的水平条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42861049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com