[英]Stacked bar chart using 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()
要繪制堆疊的條形圖,您需要在調用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.