使用matplotlib的堆积条形图

时间:2019-01-04 09:21:19

标签: python-3.x matplotlib

我需要使用matplotlib从嵌套字典中绘制堆积的条形图。我知道通过将其转换为数据框然后调用plot函数来进行绘制。我需要知道的是如何绘制它而不将其转换为数据框,即不使用pandas或numpy或任何其他模块或库。我想通过在嵌套字典上使用for循环来创建堆积的条形图。我的字典和代码尝试如下。我还想知道在创建条形图的每个部分时如何命名。

pop_data = {'Bengaluru': {2016: 2000000, 2017: 3000000, 2018: 4000000}, 'Mumbai': {2016: 5000000, 2017: 6000000, 2018: 7000000}, 'Tokyo': {2016: 8000000, 2017: 9000000, 2018: 10000000}}

sortedList = sorted(pop_data.items())
for data in sortedList:
    city = data[0]
    population = data[1]
    for year,pop in population.items():     
        plt.bar(city, pop)
plt.show()

1 个答案:

答案 0 :(得分:2)

要绘制堆叠的条形图,您需要在调用plt.bar()函数时指定底部参数

pop_data = {'Bengaluru': {2016: 2000000, 2017: 3000000, 2018: 4000000}, 
            'Mumbai': {2016: 5000000, 2017: 6000000, 2018: 7000000}, 
            'Tokyo': {2016: 8000000, 2017: 9000000, 2018: 10000000}}

year_data = {}
cities = []

for key, city_dict in pop_data.items():
    cities.append(key)
    for year, pop in sorted(city_dict.items()): 
        if year not in year_data:
            year_data[year] = []
        year_data[year].append(pop)


years = sorted(year_data.keys())
year_sum = [0]*len(cities)
bar_graphs = []

for year in years:
    graph = plt.bar(cities, year_data[year], bottom=year_sum)
    bar_graphs.append(graph[0])
    year_sum = [year_sum[i] + year_data[year][i] for i in range(len(cities))]


plt.legend(bar_graphs, years)
plt.show()

enter image description here