Pandas:如何在条形图中注释条形图(附实例)

385 阅读1分钟

你可以使用以下方法来注释pandas条形图中的条形

方法1:在简单条形图中注释条形图

ax = df.plot.bar()

ax.bar_label(ax.containers[0])

方法2:在分组条形图中注释条形图

ax = df.plot.bar()

for container in ax.containers:
    ax.bar_label(container)

下面的例子展示了如何在实践中使用每种方法。

例1:在简单条形图中注释条形图

下面的代码显示了如何在一个简单的柱状图中对柱状图进行注释:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'product': ['A', 'B', 'C', 'D', 'E'],
                   'sales': [4, 7, 8, 15, 12]})

#view DataFrame
print(df)

  product  sales
0       A      4
1       B      7
2       C      8
3       D     15
4       E     12

#create bar plot to visualize sales by product
ax = df.plot.bar(x='product', y='sales', legend=False)

#annotate bars
ax.bar_label(ax.containers[0])

pandas annotate bar plot

请注意,每个条形图的顶部都显示了销售的实际值。

例2:在分组条形图中注释条形图

下面的代码显示了如何在分组条形图中对条形进行注释:

#create DataFrame
df = pd.DataFrame({'productA': [14, 10],
                   'productB': [17, 19]},
                    index=['store 1', 'store 2'])

#view DataFrame
print(df)

         productA  productB
store 1        14        17
store 2        10        19

#create grouped bar plot
ax = df.plot.bar()

#annotate bars in bar plot
for container in ax.containers:
    ax.bar_label(container)

pandas annotate bars in grouped bar plot

请注意,注释已被添加到图中的每个条形图中。

其他资源

下面的教程解释了如何在pandas中创建其他常见的可视化效果。

如何从Pandas DataFrame创建Boxplot
如何从Pandas DataFrame创建Pie Chart
如何从Pandas DataFrame创建Histogram