如何在matplotlib的条形图中显示每个条的值
如何在matplotlib中的条形图中显示每个条的值
问题的出现原因:用户想要在matplotlib的条形图中显示每个条的值,但是不清楚如何实现。
解决方法:将数据框转换为列表,然后使用autolabel函数在条形图中显示值。
首先,将数据框转换为列表:
count = df["count"].tolist() platform = df["platform"].tolist()
然后,将列表转换为以下格式:
count = ['138','170','155','243','232'] platform =['PlayStation','PlayStation','PlayStation','PC','PlayStation']
接下来,使用以下代码实现功能:
import matplotlib.pyplot as plt from numpy.random import rand from numpy import arange count = ['138','170','155','243','232'] platform =['PlayStation','PlayStation','PlayStation','PC','PlayStation'] def autolabel(rects): for ii,rect in enumerate(rects): width = int(rect.get_width()) height = rect.get_height() yloc1=rect.get_y() + height /2.0 yloc2=rect.get_y() + height /2.0 if (width <= 5): xloc1 = width + 1 yloc2=yloc2+0.3 clr = 'black' align = 'left' else: xloc1 = 0.98*width clr = 'white' align = 'right' yloc1=rect.get_y() + height /2.0 ax.text(xloc1,yloc1, '%s'% (count[ii]),horizontalalignment=align, verticalalignment='center',color=clr,weight='bold', clip_on=True) ax.text(5,yloc2, '%s'% (platform[ii]),horizontalalignment='left', verticalalignment='center',color=clr,weight='bold', clip_on=True) val = [138,170,155,243,232] pos = [ 1996 , 1997, 1998, 1999, 2000] fig = plt.figure() ax = fig.add_subplot(111) rects = ax.barh(pos,val, align='center',height=0.4) autolabel(rects) ax.set_ylabel('Year') ax.set_xlabel('Count') ax.set_title('horizontal bar chart') ax.grid(False) plt.show()
这段代码中的关键部分是autolabel函数,它使用enumerate函数来遍历count和platform列表,并根据条件设置xloc和yloc的值,然后使用ax.text函数在条形图中显示值。
如果不想显示坐标轴,可以使用ax.axis("off")函数实现。
这样就可以在matplotlib的条形图中显示每个条的值了。