Reputation: 1139
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()
Upvotes: 0
Views: 769
Reputation: 2122
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()
Upvotes: 2