0

I need to plot a stacked bar chart from a nested dictionary using matplotlib. I know to plot it by converting it into a dataframe and then calling the plot function. What I need to know is how I can plot it without converting it into a dataframe i.e., without using pandas or numpy or any other module or library. I would like to create stacked bar chart by using for loop over a nested dictionary. My dictionary and code attempt are below. I would also like to know how I can name each section of the bar chart while creating it.

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()
DollarAkshay
  • 2,063
  • 1
  • 21
  • 39
Lax_Sam
  • 1,099
  • 2
  • 14
  • 32
  • Does this answer your question? [stacked bar plot using matplotlib](https://stackoverflow.com/questions/44309507/stacked-bar-plot-using-matplotlib) – Bill May 04 '20 at 23:59

1 Answers1

2

To plot stacked bar graphs you need to specify a bottom parameter when calling the plt.bar() function

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

DollarAkshay
  • 2,063
  • 1
  • 21
  • 39