Ozan Dogrultan
Ozan Dogrultan

Reputation: 3

Plotting multiple lists of tuples using matplotlib

I have formatted data such as this example:

datalist =  [[(u'2017-06-28', 12), (u'2017-06-29', 0), (u'2017-06-30', 17), (u'2017-06-26', 17), (u'2017-06-27', 8), (u'2017-07-02', 0), (u'2017-07-01', 2)], [(u'2017-06-28', 6), (u'2017-06-29', 3), (u'2017-06-30', 13), (u'2017-06-26', 12), (u'2017-06-27', 9), (u'2017-07-02', 1), (u'2017-07-01', 2)]]

which is basically a list of lists of tuples - ([[(date, value), …], [(date, value), …]]. I would like to plot this data such that dates will correspond x-axis labels and values will be heights of my bars for my bar chart. What is the best -or less time consuming way to achieve this? Any help is appreciated. Thanks in advance.

Upvotes: 0

Views: 853

Answers (1)

Vinícius Figueiredo
Vinícius Figueiredo

Reputation: 6508

If you want a bar plot of the first element of your outermost list, you should get your values into lists using a simple list comprehension, but to convert the date values directly into datetime you can do something like the shown below. If you need the values for the second element, just change datalist[0] to datalist[1].

import datetime
x = [datetime.datetime.strptime(tup[0],"%Y-%m-%d") for tup in datalist[0]]
y = [tup[1] for tup in datalist[0]] 

And then just call plt.bar():

plt.bar(x,y)
plt.show()

To plot multiple bar charts with datetime one can do the following:

x1 = [datetime.datetime.strptime(tup[0],"%Y-%m-%d") for tup in datalist[0]]
x2 = [datetime.datetime.strptime(tup[0],"%Y-%m-%d") for tup in datalist[1]]
y1 = [tup[1] for tup in datalist[0]]
y2 = [tup[1] for tup in datalist[1]]

plt.bar(x1,y1,.1,color='blue')
plt.bar([i+datetime.timedelta(.1) for i in x2],y2,.1,color='red')
plt.show()

If you don't know how many bar you'll need you just need to make the last shown code in a for loop, storing the data in a list of lists(so that, for example, x4 is xarr3), something like this:

xarr = [x1,x2]
yarr = [y1,y2]

for i in range(len(datalist)):
    plt.bar([j+datetime.timedelta((i-1)*.1) for j in xarr[i]],yarr[i], width = .1)

plt.show()

enter image description here

Upvotes: 2

Related Questions