[英]Stacked bar plot in python / plotly (express): grouping / ordering of bars
[英]How to get stacked bars in python 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)
我對堆積酒吧會更感興趣。 例如,我希望第一個條由兩個堆疊的條組成,第一個條的高度為2(因為與該條相關的兩個'a'屬性),另一個條的高度為1。 因此,第一個條形圖可以包含兩個堆疊的條形圖; 一根高度為2的紅色條和一根高度為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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.