简体   繁体   English

如何(迭代地)在 Python 中的分组条形图的条形旁边写一个字符串?

[英]How to (iteratively) write a string alongside the bars of a grouped bar plot in Python?

I have coded a horizontal grouped bar plot using Python.我使用 Python 编写了一个水平分组条形图。 My requirement is that I want to write the number associated with each bar alongside the bars.我的要求是我想在条形旁边写下与每个条形相关的数字。 I have seen problems similar to this on the internet.我在网上看到过类似的问题。 But I am not sure how to carry out the task in my specific case where there are grouped bars.但是我不确定如何在有分组条的特定情况下执行任务。 The following is my code:以下是我的代码:

在此处输入图像描述

# importing package
import matplotlib.pyplot as plt
import pandas as pd
  
# create data
df = pd.DataFrame([['A', 10, 20, 10, 30], ['B', 20, 25, 15, 25], ['C', 12, 15, 19, 6],
                   ['D', 10, 29, 13, 19]],
                  columns=['Team', 'Round 1', 'Round 2', 'Round 3', 'Round 4'])
# view data
print(df)


  
# plot grouped bar chart
ax=df.plot.barh(x='Team',        
        stacked=False,
        log=True,
        title='Grouped Bar Graph with dataframe')

The updates required is added here.此处添加所需的更新。 Note that I have increased the figure size so you can see the numbers and moved the legend box outside the plot.请注意,我增加了图形大小,以便您可以看到数字并将图例框移到绘图之外。 At least a part of the solution is available here .至少有一部分解决方案在这里可用。 If you have the newer version of matplotlib (3.4.2 or later), you can also use the bar_label feature如果您有较新版本的 matplotlib(3.4.2 或更高版本),您还可以使用bar_label功能

# importing package
import matplotlib.pyplot as plt
import pandas as pd
  
# create data
df = pd.DataFrame([['A', 10, 20, 10, 30], ['B', 20, 25, 15, 25], ['C', 12, 15, 19, 6],
                   ['D', 10, 29, 13, 19]],
                  columns=['Team', 'Round 1', 'Round 2', 'Round 3', 'Round 4'])
# view data
print(df)
  
# plot grouped bar chart
ax=df.plot.barh(x='Team', stacked=False, figsize=(10,7), log = True,  
                title='Grouped Bar Graph with dataframe')

# Move legend outside the graph
ax.legend(bbox_to_anchor=(1.01, 1))

# Add labels
for p in ax.patches:
    ax.annotate(str(p.get_width()), (p.get_x() + p.get_width(), p.get_y()-0.075), xytext=(5, 10), textcoords='offset points')

Output输出

图形

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM