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()
1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

7 Comments

That solved it! Thank you! Can you please answer the second part of the question? How to add the city name to each section?
The city name already shows up for each bar on the plot. Are you trying to group it by year?
No. My bad! I mean I want the year name on the sections.
I have modified the answer.
Added a legend.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.