While this code:
import plotly
from plotly.graph_objs import *
import pandas as pd
import datetime
date = ['2017-01-01', '2017-01-04', '2017-01-05', '2017-02-01', '2017-02-10']
date_dt = map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d'), date)
attribute = ['a', 'b', 'a', 'a', 'b']
json_file = {'attribute':attribute}
df = pd.DataFrame(json_file, index=date_dt)
weekly_summary = pd.DataFrame()
weekly_summary['summation'] = df.attribute.resample('W', closed='left').count()
trace1 = Bar(
x=weekly_summary.index.tolist(),
y=weekly_summary.summation
)
layout = Layout(
xaxis=XAxis(
ticks=weekly_summary.index.tolist(),
tickvals=weekly_summary.index.tolist(),
),
yaxis=YAxis(
ticks=weekly_summary.summation
)
)
data = Data([trace1])
figure = Figure(data=data, layout=layout)
plotly.offline.plot(figure)
will produce the following graph, which is a counting of objects per week:
I would be more interested in having stacked bars. For example I would like the first bar to consist of two stacked bars , the first one with height two (because there are two 'a' attributes related to that bar) and one bar with height one. So, the first bar could consist of two stacked bars; one red bar with height two and one blue bar with height one. How can I achieve that?
I managed to do something, but it is quite tedious. Here's the code and the result:
import plotly
from plotly.graph_objs import *
import matplotlib.pyplot as plt
import pandas as pd
import datetime
date = ['2017-01-01', '2017-01-04', '2017-01-05', '2017-02-01', '2017-02-10']
date_dt = map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d'), date)
attribute = ['a', 'b', 'a', 'a', 'b']
json_file = {'attribute':attribute}
df = pd.DataFrame(json_file, index=date_dt)
first_df = df[df['attribute'] == 'a'].copy()
first_df.reindex([date_dt])
first_df_modified = pd.DataFrame()
first_df_modified['counter'] = first_df.attribute.resample('W', closed='left').count()
second_df = df[df['attribute'] == 'b'].copy()
second_df.reindex([date_dt])
second_df_modified = pd.DataFrame()
second_df_modified['counter'] = second_df.attribute.resample('W', closed='left').count()
trace1 = Bar(
x=first_df_modified.index,
y=first_df_modified.counter,
name='a'
)
trace2 = Bar(
x=second_df_modified.index,
y=second_df_modified.counter,
name='b'
)
layout = Layout(
xaxis=XAxis(
ticks=second_df_modified.index,
tickvals=second_df_modified.index,
),
barmode='stack'
)
data = Data([trace1, trace2])
figure = Figure(data=data, layout=layout)
plotly.offline.plot(figure)
with graph: but I think there should be a smarter way to do that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.