bar chart with Matplotlib

孤街醉人 提交于 2020-05-30 02:46:08

问题


Here is my data structure:

data = {'2013': {1:25,2:81,3:15}, '2014': {1:28, 2:65, 3:75}, '2015': {1:78,2:91,3:86 }}

My x-axis is the number [1,2,3]

My y-axis is the quantity of each number. For example: In 2013, 1 is x axis while its quantity is 25.

Print each individual graph for each year

I would like to graph a bar chart, which uses matplotlib with legend on it.


回答1:


import matplotlib.pyplot as plt
import pandas as pd

data = {'2013': {1:25,2:81,3:15}, '2014': {1:28, 2:65, 3:75}, '2015': {1:78,2:91,3:86 }}

df = pd.DataFrame(data)

df.plot(kind='bar')

plt.show()

I like pandas because it takes your data without having to do any manipulation to it and plot it.




回答2:


You can access the keys of a dictionary via dict.keys() and the values via dict.values()

If you wanted to plot, say, the data for 2013 you can do:

import matplotlib.pyplot as pl
x_13 = data['2013'].keys()
y_13 = data['2013'].values()
pl.bar(x_13, y_13, label = '2013')
pl.legend()

That should do the trick. More elegantly, do can simply do:

year = '2013'
pl.bar(data[year].keys(), data[year].values(), label=year)

which woud allow you to loop it:

for year in ['2013','2014','2015']:
    pl.bar(data[year].keys(), data[year].values(), label=year)


来源:https://stackoverflow.com/questions/32956199/bar-chart-with-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!