繁体   English   中英

Python matplotlib如何在堆积条形图的顶部添加总值

[英]Python matplotlib how to add total value on top of stacked bar chart

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

colors = dict()
colors['sats'] = 'b'
colors['cache'] = 'orange'
colors['3h'] = 'k'
colors['memory'] = 'g'
colors['integer'] = 'r'
#####################################
sz = np.array([ 2.,  4.,  6.,  8.])


t1 = np.array([  5.9718688 ,  13.23303584,  23.9000157 ,  37.94884449])
t2 = np.array([  7.38123836,  16.45442501,  29.56201748,  46.60925727])
t3 = np.array([   8.87223103,   19.89443438,   36.27273578,   57.65372517])
t4 = np.array([   9.88902238,   22.11467593,   40.2324561 ,   63.90151877])
t4 -= t3
t3 -= t2
t2 -= t1
plt.bar(sz, t1, color=colors['sats'], edgecolor='white', label="SATS")
plt.bar(sz, t2, bottom=np.array(t1), color=colors['cache'], edgecolor='white', label="Caching values")
plt.bar(sz, t3, bottom=np.array(t1)+np.array(t2), color=colors['memory'], edgecolor='white', label="Optimizing memory access")
plt.bar(sz, t4, bottom=np.array(t1)+np.array(t2)+np.array(t3), color=colors['integer'], edgecolor='white', label="Integer SATS")
plt.ylim(top=70)
plt.xlabel('Filter radius')
plt.ylabel('Cumulative speedup ratio')
plt.legend()
plt.savefig("benchmark-cpu-relativit.pdf", transparent = True, bbox_inches = 'tight', pad_inches = 0)
plt.close()

在所有条形顶部添加文本

所以我想在条形顶部添加总值。 例如,第一个柱应该有 10,第二个柱应该有 22,...

我试过barh但我得到错误TypeError: bar() got multiple values for keyword argument 'bottom'

我让我的一个功能。 我的下一个目标是获取案例县中所有区域的总数,并将其显示出来。 随意取出功能方面。 不需要。

这部分我相信你有,但想把所有东西放在一起

def getTotalCounts(dfSS): 
county = dfSS.groupby(['County']).count()  # this will put "COUNTY"on Y-Axis and  
                                           #counts all the values from other columns
counts = county.loc[:,"Number of Vehicles Removed"]  # left side :  all rows , right side: is the column we want to look at. 

counts.plot(kind='bar', x='county', y='counts') #this makes our bar chart from the 
                                                #data.

#这将每个部分的总数添加到条形图的顶部,居中

   for i in range(len(county)):   
    plt.text(i, counts[i], counts[i], ha='center', va='bottom') #i for each index. [i] 
     # for the height of counts(the bar/number of "whatever you're counting")
     # the 2nd count[i] is for displaying numbers but we can put "text" there

如果需要更多附加组件

plt.title('Total Vehicle Removal Counts By County') #title the bar chart
plt.xlabel("Counties")  # labels the X-Axis on our graph
plt.ylabel('Vehicles Removed')  # labels the Y-Axis on our graph
plt.legend()  # add a legend for our graph

# plt.xticks([1,2,3]) # change to x tick values and how much they go or down by
# plt.yticks([1,2,3]) # change to y tick values and how much they go or down by

plt.show()  # show or print out the graph to view

旁注这不适用于堆叠条形图,而是用于条形图中的单个条形。

暂无
暂无

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

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