somerandomguy
somerandomguy

Reputation: 323

Create a stacked graph or bar graph using plotly in python

I have data like this :

[ ('2018-04-09', '10:18:11',['s1',10],['s2',15],['s3',5])

('2018-04-09', '10:20:11',['s4',8],['s2',20],['s1',10])

('2018-04-10', '10:30:11',['s4',10],['s5',6],['s6',3]) ]

I want to plot a stacked graph preferably of this data.

X-axis will be time, it should be like this enter image description here

I created this image in paint just to show. X axis will show time like normal graph does( 10:00 ,April 3,2018).

I am stuck because the string value (like 's1',or 's2' ) will change in differnt bar graph.

Just to hard code and verify,I try this:

import plotly
import plotly.graph_objs as go
import matplotlib.pyplot as plt
import matplotlib
plotly.offline.init_notebook_mode()

def createPage():

    graph_data = []

    l1=[('com.p1',1),('com.p2',2)('com.p3',3)]

    l2=[('com.p1',1),('com.p4',2)('com.p5',3)]

    l3=[('com.p2',8),('com.p3',2)('com.p6',30)]

    trace_temp = go.Bar(
                x='2018-04-09 10:18:11',
                y=l1[0],
                name = 'top',
                )

    graph_data.append(trace_temp)


    plotly.offline.plot(graph_data, filename='basic-scatter3.html')

createPage()

Error I am getting is Tuple Object is not callable.

So can someone please suggest some code for how I can plot such data. If needed,I may store data in some other form which may be helpful in plotting.

Edit : I used the approach suggested in accepted answer and succeed in plotting using plotly like this

fig=df.iplot(kin='bar',barmode='stack',asFigure=True)

plotly.offline.plt(fig,filename="stack1.html)

However I faced one error:

1.When Time intervals are very close,Data overlaps on graph. Is there a way to overcome it.

Upvotes: 1

Views: 2274

Answers (1)

Mr. T
Mr. T

Reputation: 12410

You could use pandas stacked bar plot. The advantage is that you can create with pandas easily the table of column/value pairs you have to generate anyhow.

from matplotlib import pyplot as plt
import pandas as pd

all_data = [('2018-04-09', '10:18:11', ['s1',10],['s2',15],['s3',5]),
            ('2018-04-09', '10:20:11', ['s4',8], ['s2',20],['s1',10]),
            ('2018-04-10', '10:30:11', ['s4',10],['s5',6], ['s6',3]) ]

#load data into dataframe
df = pd.DataFrame(all_data, columns = list("ABCDE"))
#combine the two descriptors
df["day/time"] = df["A"] + "\n" + df["B"]
#assign each list to a new row with the appropriate day/time label
df = df.melt(id_vars = ["day/time"], value_vars = ["C", "D", "E"])
#split each list into category and value
df[["category", "val"]] = pd.DataFrame(df.value.values.tolist(), index = df.index)
#create a table with category-value pairs from all lists, missing values are set to NaN
df = df.pivot(index = "day/time", columns = "category", values = "val")
#plot a stacked bar chart 
df.plot(kind = "bar", stacked = True)
#give tick labels the right orientation
plt.xticks(rotation = 0)
plt.show()

Output: enter image description here

Upvotes: 2

Related Questions