0
votes

Hi i am to create stacked bar chart from data in a CSV file,producing chart similar to this graph

Here is the data

Date,Kitchen,Laundry,Aircon&heater,Others
Jan/2010,53.887,56.568,395.913,483.293
Feb/2010,49.268,53.590,411.714,409.956
Mar/2010,35.089,60.872,324.352,382.285
Apr/2010,38.196,36.476,336.091,328.872
May/2010,48.107,52.376,364.625,349.765
Jun/2010,65.747,47.675,306.934,277.734
Jul/2010,17.667,34.359,192.912,291.525
Aug/2010,12.499,26.983,160.189,168.719
Sep/2010,36.865,32.508,257.861,277.923
Oct/2010,48.199,60.220,315.669,441.461
Nov/2010,45.082,41.897,237.124,394.402

i know how to create charts/stacking it and stuffs,the problem is i have no idea how to import and use the data from the file to plot it.Help?

1
For reading csv files: docs.python.org/2/library/csv.htmlsavanto
well reading isn't exactly the main question here,its more of how to use it to plot chartsuser3555206
@user3555206, "i know how to create charts/stacking it and stuffs" then what is your question?tuxuday
@tuxuday using the data from a csv file to plotuser3555206
This sounds almost like a homework question. You should at least show some effort wrt figuring this out yourself.stephenfin

1 Answers

2
votes

Hey you can also use numpy.loadtxt to readin your data. I tried it like this, hope this is what you want:

import matplotlib.pyplot as plt
import numpy as np

# import data with loadtxt, but only the relevant floats. 
# data.csv is the file as you have given it above
data = np.loadtxt('data.csv', delimiter=',', skiprows = 1, usecols = range(1,5))
data = data.transpose()

# import the tick labels
xt = np.loadtxt('data.csv', dtype='str', delimiter=',', skiprows = 1, usecols = (0,))

the rest is plotting bar charts as you did:

width = 0.45
ind = np.arange(11) + 0.75

fig, ax = plt.subplots(1,1)
p0 = ax.bar(ind, data[0],  width, color = 'cyan')
p1 = ax.bar(ind, data[1], width, bottom = data[0], color = 'violet')
p2 = ax.bar(ind, data[2], width, bottom = data[0] + data[1], color = 'g')
p3 = ax.bar(ind, data[3], width, bottom = data[0] + data[1] + data[2], color = 'r')

ax.set_ylabel('kWh')
ax.set_xlabel('month')
ax.set_xticks (ind + width/2.)
ax.set_xticklabels( xt, rotation = 70 )

fig.legend( (p0[0], p1[0], p2[0], p3[0]), ('kitchen', 'laundry', 'aircon&heater', 'other') )
fig.tight_layout()
fig.show()

This gave me the following plot: enter image description here