2017-10-08 288 views
0

儘管此代碼:如何獲得堆疊條形plotly

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) 

會產生如下圖,這是每週對象計數: enter image description here

我會更感興趣的有堆積的酒吧。例如,我希望第一個酒吧由兩個堆疊的酒吧組成,第一個酒吧的高度爲2(因爲有兩個與該酒吧相關的「a」屬性),另一個酒吧的高度爲一。所以,第一個酒吧可以由兩個堆疊的酒吧組成;一個高度爲2的紅色條和一個高度爲1的藍色條。我怎樣才能做到這一點?

回答

1

我設法做了一些事情,但它非常繁瑣。下面的代碼和結果:

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) 

與圖形: enter image description here 但我認爲應該做一個更聰明的方法。