Python 3.x 使用matplotlib的堆叠条形图

Python 3.x 使用matplotlib的堆叠条形图,python-3.x,matplotlib,Python 3.x,Matplotlib,我需要使用matplotlib从嵌套字典中绘制堆叠条形图。我知道通过将其转换为数据帧,然后调用plot函数来绘制它。我需要知道的是如何在不将其转换为数据帧的情况下绘制它,即不使用pandas、numpy或任何其他模块或库。我想通过使用嵌套字典上的for循环创建堆叠条形图。下面是我的字典和代码尝试。我还想知道如何在创建条形图时命名条形图的每个部分 pop_data = {'Bengaluru': {2016: 2000000, 2017: 3000000, 2018: 4000000}, 'Mum

我需要使用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()

要绘制堆叠条形图,需要在调用函数时指定底部参数


要绘制堆叠条形图,调用函数时需要指定底部参数


这就解决了问题!非常感谢。你能回答问题的第二部分吗?如何将城市名称添加到每个部分?城市名称已显示在绘图上的每个栏上。你想按年份分组吗?不,我的错!我的意思是我想在章节上注明年份名称。我已经修改了答案。添加了一个图例。这就解决了问题!非常感谢。你能回答问题的第二部分吗?如何将城市名称添加到每个部分?城市名称已显示在绘图上的每个栏上。你想按年份分组吗?不,我的错!我的意思是我想在章节上写上年份名称。我已经修改了答案。添加了一个图例。这能回答你的问题吗?这回答了你的问题吗?
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()