如何向条形图添加多个注释

sri*_*avi 6 python matplotlib bar-chart pandas

我想将百分比值 - 除了计数 - 添加到我的熊猫条形图中。但是,我无法这样做。我的代码如下所示,到目前为止,我可以获得要显示的计数值。有人可以帮我在每个条形显示的计数值旁边/下方添加相对百分比值吗?

import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')

import seaborn as sns
sns.set_style("white")

fig = plt.figure()
fig.set_figheight(5)
fig.set_figwidth(10)

ax = fig.add_subplot(111)

counts = [29227, 102492,  53269, 504028, 802994]

y_ax = ('A','B','C','D','E')
y_tick = np.arange(len(y_ax))

ax.barh(range(len(counts)), counts, align = "center", color = "tab:blue")
ax.set_yticks(y_tick)
ax.set_yticklabels(y_ax, size = 8)

#annotate bar plot with values
for i in ax.patches:
    ax.text(i.get_width()+.09, i.get_y()+.3, str(round((i.get_width()), 1)), fontsize=8)

sns.despine()
plt.show();
Run Code Online (Sandbox Code Playgroud)

我的代码的输出如下所示。如何在显示的每个计数值旁边添加 % 值?

在此处输入图片说明

Tre*_*ney 5

pandas

  • 测试过 pandas v1.2.4

导入和加载数据

import pandas as pd
import matplotlib.pyplot as plt

# create the dataframe from values in the OP
counts = [29227, 102492,  53269, 504028, 802994]
df = pd.DataFrame(data=counts, columns=['counts'], index=['A','B','C','D','E'])

# add a percent column
df['%'] = df.counts.div(df.counts.sum()).mul(100).round(2)

# display(df)
   counts      %
A   29227   1.96
B  102492   6.87
C   53269   3.57
D  504028  33.78
E  802994  53.82
Run Code Online (Sandbox Code Playgroud)

matplotlib从 3.4.2 版开始绘制使用

ax = df.plot(kind='barh', y='counts', figsize=(10, 5), legend=False, width=.75,
             title='This is the plot generated by all code examples in this answer')

# customize the label to include the percent
labels = [f' {v.get_width()}\n {df.iloc[i, 1]}%' for i, v in enumerate(ax.containers[0])]

# set the bar label
ax.bar_label(ax.containers[0], labels=labels, label_type='edge', size=13)

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

注释资源 - 来自 matplotlib v3.4.2

matplotlib3.4.2 版本之前的绘图使用

# plot the dataframe
ax = df.plot(kind='barh', y='counts', figsize=(10, 5), legend=False, width=.75)
for i, y in enumerate(ax.patches):

    # get the percent label
    label_per = df.iloc[i, 1]
    
    # add the value label
    ax.text(y.get_width()+.09, y.get_y()+.3, str(round((y.get_width()), 1)), fontsize=10)
    
    # add the percent label here
    ax.text(y.get_width()+.09, y.get_y()+.1, str(f'{round((label_per), 2)}%'), fontsize=10)

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.show()
Run Code Online (Sandbox Code Playgroud)

原答案没有 pandas

  • 测试过 matplotlib v3.3.4
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10, 5))

counts = [29227, 102492,  53269, 504028, 802994]

# calculate percents
percents = [100*x/sum(counts) for x in counts]

y_ax = ('A','B','C','D','E')
y_tick = np.arange(len(y_ax))

ax.barh(range(len(counts)), counts, align = "center", color = "tab:blue")
ax.set_yticks(y_tick)
ax.set_yticklabels(y_ax, size = 8)

#annotate bar plot with values
for i, y in enumerate(ax.patches):
    label_per = percents[i]
    ax.text(y.get_width()+.09, y.get_y()+.3, str(round((y.get_width()), 1)), fontsize=10)
    # add the percent label here
    # ax.text(y.get_width()+.09, y.get_y()+.3, str(round((label_per), 2)), ha='right', va='center', fontsize=10)
    ax.text(y.get_width()+.09, y.get_y()+.1, str(f'{round((label_per), 2)}%'), fontsize=10)

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.show()
Run Code Online (Sandbox Code Playgroud)
  • 你可以玩定位。
  • JohanC提到的其他格式选项
  • 在一个字符串中打印文本的两个部分,\n中间有一个“自然”行距:
  • str(f'{round((y.get_width()), 1)}\n{round((label_per), 2)}%')
  • ax.text(..., va='center') 垂直居中并能够使用稍大的字体。
  • ax.set_xlim(0, max(counts) * 1.18) 为文本获得更多空间。
  • 用空格开始每一行文本以获得自然的“水平”填充。
  • str(f' {round((label_per), 2)}%'),注意前面的空格{
  • y.get_width()+.09非常接近y.get_width()这些值在数万的时候。

在此处输入图片说明