带注释的水平条形图 [英] Horizontal barplot with annotations
问题描述
当我每次运行此代码时,python内核显然死亡并死亡时,我已成功运行了该代码: 代码有问题还是问题更深?我可以毫无问题地运行其他笔记本.
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? 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.
这是使用Seaborn的解决方案:
Here is a solution using 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')
创建:
更新: 为了给文本加上颜色:
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])
这篇关于带注释的水平条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!