将数据标签添加到MatPlotLib中的分组条形图 [英] Add data label to grouped bar chart in MatPlotLib

查看:104
本文介绍了将数据标签添加到MatPlotLib中的分组条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法找到并自定义了一些 matplotlib 代码来创建分组条形图.但是,该代码的顶部没有标签.我尝试了几种方法,但我只是没有做对.

我的最终目标将是:

  1. 在每个栏的顶部添加数据标签
  2. 摆脱外部和y轴标签周围的黑色边框

非常感谢任何帮助(尤其是#1)!

代码:

#Code 改编自:#https://chrisalbon.com/python/matplotlib_grouped_bar_plot.html#matplotlib 在线将熊猫作为pd导入导入matplotlib.pyplot作为plt将numpy导入为npraw_data = {'plan_type': ['A1', 'A2', 'A3', 'A4', 'A5', 'A6'],'A组':[100, 0, 0, 0, 0, 0],B组":[48, 16, 9, 22, 5, 0],"C组":[18、28、84、34、11、0],D组":[49, 13, 7, 23, 6, 0],"E组":[57、16、9、26、3、0]}df = pd.DataFrame(raw_data,列= ['plan_type','Group B','Group C','Group D','Group E'])df2 = pd.DataFrame(raw_data,列= ['plan_type','Group A'])#设置钢筋的位置和宽度pos = list(range(len(df ['Group B'])))宽度= 0.2# 绘制条形图图, ax = plt.subplots(figsize=(7, 2))#这会创建另一个共享相同 x 轴的 y 轴#使用A组数据创建一个条形,# 在位置 pos + 一些宽度缓冲区,plt.bar(pos,#使用df ['Group E']数据,df2 ['Group A'],宽度#宽度*8,#含alpha 0.5阿尔法=1,# 带颜色color ='#E6E9ED',# 标签为 plan_type 中的第四个值标签=df2['plan_type'][0])# 创建一个包含 B 组数据的条形图,#在位置pos,plt.bar(pos,#using df ['Group B']数据,df['B组'],宽度#宽度,#与alpha 1阿尔法=1,# 带颜色颜色='#900C3F',#带有标签plan_type中的第一个值label=df['plan_type'][0])#使用C组数据创建一个条形,# 在位置 pos + 一些宽度缓冲区,plt.bar([p +位置中p的宽度],#using df ['Group C']数据,df['C组'],宽度#宽度,#与alpha 1alpha = 1.0,# 带颜色color ='#C70039',# 标签为 plan_type 中的第二个值label = df ['plan_type'] [1])#使用D组数据创建一个条形图,# 在位置 pos + 一些宽度缓冲区,plt.bar([p + width*2 for p in pos],#使用 df['Group D'] 数据,df['D组'],宽度#宽度,#与alpha 1阿尔法=1,# 带颜色颜色='#FF5733',#带有标签plan_type中的第三个值label = df ['plan_type'] [2])#使用E组数据创建一个条形图,# 在位置 pos + 一些宽度缓冲区,plt.bar([p + width*3 for p in pos],#使用df ['Group E']数据,df['E组'],宽度#宽度,#与alpha 1阿尔法=1,# 带颜色color ='#FFC300',# 标签为 plan_type 中的第四个值label=df['plan_type'][3])#设置y轴标签ax.set_ylabel('Percent')#设置图表标题ax.set_title('A GRAPH - YAY!', fontweight = "bold")#设置x刻度的位置ax.set_xticks([p + 1.5 *位置中p的宽度])#设置x刻度的标签ax.set_xticklabels(df ['plan_type'])# 设置 x 轴和 y 轴限制plt.xlim(min(pos)-width, max(pos)+width*5)plt.ylim([0, 100] )#plt.ylim([0, max(df['Group B'] + df['Group C'] + df['Group D'] + df['Group E'])] )#添加图例并显示图.上中心位置,5 列,展开以适合一行.plt.legend(['A组','B组','C组','D组','E组'], loc='upper center', ncol=5, mode='expand', fontsize ='x-small')#plt.grid()->这会添加一个网格,但我不想要那个.plt.show()plt.savefig("PlanOffered.jpg")

解决方案

解决方案与此问题类似:

我稍微简化了代码.

将pandas导入为pd导入matplotlib.pyplot作为plt将numpy导入为npraw_data = {'plan_type': ['A1', 'A2', 'A3', 'A4', 'A5', 'A6'],'A组':[100, 0, 0, 0, 0, 0],B组":[48, 16, 9, 22, 5, 0],"C组":[18、28、84、34、11、0],D组":[49, 13, 7, 23, 6, 0],"E组":[57、16、9、26、3、0]}df2 = pd.DataFrame(raw_data,列= ['plan_type','Group A'])df = pd.DataFrame(raw_data,列 = ['plan_type', 'Group B', 'Group C', 'Group D', 'Group E'])ax = df2.plot.bar(rot = 0,color ='#E6E9ED',width = 1)ax = df.plot.bar(rot=0, ax=ax, color=["#900C3F", '#C70039', '#FF5733', '#FFC300'],宽度= 0.8)对于 ax.patches[1:] 中的 p:h = p.get_height()x = p.get_x()+ p.get_width()/2.如果 h != 0:ax.annotate(%g"%p.get_height(),xy =(x,h),xytext =(0,4),旋转度= 90,textcoords="offset points", ha="center", va="bottom")ax.set_xlim(-0.5, 无)ax.margins(y=0)ax.legend(ncol = len(df.columns),loc =左下",bbox_to_anchor =(0,1.02,1,0.08),borderaxespad = 0,mode ="expand")ax.set_xticklabels(df["plan_type"])plt.show()

I managed to find and customize some matplotlib code to create grouped bar charts. However, the code doesn't have labels at the top. I have tried several approaches, but I'm just not getting it right.

My end goal will be:

  1. Add data labels to the top of each bar
  2. Get rid of the black border around the outside and the y-axis labels

Any help (especially with #1) is greatly appreciated!

The code:

#Code adapted from:  
#https://chrisalbon.com/python/matplotlib_grouped_bar_plot.html
#matplotlib online

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np


raw_data = {'plan_type': ['A1', 'A2', 'A3', 'A4', 'A5', 'A6'],
        'Group A':     [100, 0, 0, 0, 0, 0],
        'Group B':     [48, 16, 9, 22, 5, 0],
        'Group C':     [18, 28, 84, 34, 11, 0],
        'Group D': [49, 13, 7, 23, 6, 0],
        'Group E':          [57, 16, 9, 26, 3, 0]

    }
df = pd.DataFrame(raw_data, columns = ['plan_type', 'Group B', 'Group C', 'Group D', 'Group E'])


df2 =pd.DataFrame(raw_data, columns = ['plan_type', 'Group A'])



# Setting the positions and width for the bars
pos = list(range(len(df['Group B'])))
width = 0.2

# Plotting the bars
fig, ax = plt.subplots(figsize=(7, 2))


#This creates another y-axis that shares the same x-axis


# Create a bar with Group A data,
# in position pos + some width buffer,
plt.bar(pos,
    #using df['Group E'] data,
    df2['Group A'],
    # of width
    width*8,
    # with alpha 0.5
    alpha=1,
    # with color
    color='#E6E9ED',
    # with label the fourth value in plan_type
    label=df2['plan_type'][0])


# Create a bar with Group B data,
# in position pos,
plt.bar(pos,
    #using df['Group B'] data,
    df['Group B'],
    # of width
    width,
    # with alpha 1  
    alpha=1,
    # with color
    color='#900C3F',
    # with label the first value in plan_type
    label=df['plan_type'][0])

# Create a bar with Group C data,
# in position pos + some width buffer,
plt.bar([p + width for p in pos],
    #using df['Group C'] data,
    df['Group C'],
    # of width
    width,
    # with alpha 1
    alpha=1.0,
    # with color
    color='#C70039',
    # with label the second value in plan_type
    label=df['plan_type'][1])

# Create a bar with Group D data,
# in position pos + some width buffer,
plt.bar([p + width*2 for p in pos],
    #using df['Group D'] data,
    df['Group D'],
    # of width
    width,
    # with alpha 1
    alpha=1,
    # with color
    color='#FF5733',
    # with label the third value in plan_type
    label=df['plan_type'][2])

# Create a bar with Group E data,
# in position pos + some width buffer,
plt.bar([p + width*3 for p in pos],
    #using df['Group E'] data,
    df['Group E'],
    # of width
    width,
    # with alpha 1
    alpha=1,
    # with color
    color='#FFC300',
    # with label the fourth value in plan_type
    label=df['plan_type'][3])


# Set the y axis label
ax.set_ylabel('Percent')

# Set the chart's title
ax.set_title('A GRAPH - YAY!', fontweight = "bold")

# Set the position of the x ticks
ax.set_xticks([p + 1.5 * width for p in pos])

# Set the labels for the x ticks
ax.set_xticklabels(df['plan_type'])

# Setting the x-axis and y-axis limits
plt.xlim(min(pos)-width, max(pos)+width*5)
plt.ylim([0, 100] )
#plt.ylim([0, max(df['Group B'] + df['Group C'] + df['Group D'] + df['Group E'])] )

# Adding the legend and showing the plot.  Upper center location, 5 columns, 
Expanded to fit on one line.
plt.legend(['Group A','Group B', 'Group C', 'Group D', 'Group E'], loc='upper center', ncol=5, mode='expand', fontsize  ='x-small')

#plt.grid()  --> This would add a Grid, but I don't want that.

plt.show()
plt.savefig("PlanOffered.jpg")

解决方案

The solution is similar to the one in this question: Adding value labels on a matplotlib bar chart

However I provide you with an example which uses your own type of plot, and thus makes it easier to understand.

The general idea in order to obtain labels on top of bars, is to iterate over the patches within the axes and annotate them with their respecticve heights.

I simplified the code a bit.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

raw_data = {'plan_type': ['A1', 'A2', 'A3', 'A4', 'A5', 'A6'],
        'Group A':     [100, 0, 0, 0, 0, 0],
        'Group B':     [48, 16, 9, 22, 5, 0],
        'Group C':     [18, 28, 84, 34, 11, 0],
        'Group D': [49, 13, 7, 23, 6, 0],
        'Group E':          [57, 16, 9, 26, 3, 0]

    }
df2 =pd.DataFrame(raw_data, columns = ['plan_type', 'Group A'])
df = pd.DataFrame(raw_data, 
                  columns = ['plan_type', 'Group B', 'Group C', 'Group D', 'Group E'])

ax = df2.plot.bar(rot=0,color='#E6E9ED',width=1)
ax = df.plot.bar(rot=0, ax=ax, color=["#900C3F", '#C70039', '#FF5733', '#FFC300'], 
                 width = 0.8 )

for p in ax.patches[1:]:
    h = p.get_height()
    x = p.get_x()+p.get_width()/2.
    if h != 0:
        ax.annotate("%g" % p.get_height(), xy=(x,h), xytext=(0,4), rotation=90, 
                   textcoords="offset points", ha="center", va="bottom")

ax.set_xlim(-0.5, None)
ax.margins(y=0)
ax.legend(ncol=len(df.columns), loc="lower left", bbox_to_anchor=(0,1.02,1,0.08), 
          borderaxespad=0, mode="expand")
ax.set_xticklabels(df["plan_type"])
plt.show()

这篇关于将数据标签添加到MatPlotLib中的分组条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆