Usage data
Source code
gen_calmap
def gen_calmap(df,column_name_lst,aggr='sum',height= 260,width = 900):
try:
for column_name in column_name_lst:
# heatmap_df_lst generation
heatmap_df_lst = _calender_heatmap_df(df,column_name,aggr)
for heatmap_df in heatmap_df_lst:
fig = px.imshow(heatmap_df[0],
x=heatmap_df[0].columns.unique(),
y=heatmap_df[0].index.unique(),
labels={'y':'Weekday','x':'Week','color':column_name},
width=width,
height=height,
aspect='auto',
)
#Insert a gap between cells
fig.data[0]['ygap']=1
fig.data[0]['xgap']=1
fig.update_traces(
text = heatmap_df[1],
hovertemplate="Date: %{text} <br>Week: %{x} <br>Weekday: %{y} <br> "+ column_name +": %{z}"
)
fig.show()
except:
print('Failed to generate calmap.')
def _calender_heatmap_df(df,column_name,aggr='sum'):
heatmap_df_lst =[]
#DataFrame regeneration
data = pd.DataFrame(eval("df[column_name].resample('D').{}()".format(aggr)))
data.index = pd.to_datetime(data.index)
## add data
data['week'] = pd.to_datetime(data.index).strftime('Week:%W')
data['weekday'] = pd.to_datetime(data.index).weekday
data['date'] = pd.to_datetime(data.index).strftime('%Y/%m/%d')
weekday_dic = {0:'Mon',1:'Tue',2:'Wed',3:'Thr',4:'Fri',5:'Sat',6:'Sun'}
#Data expansion
for year in data.index.year.unique():
#heatmap generation
heatmap_df = data.loc[data.index.year == year,:].pivot_table(index='weekday',columns='week',values=column_name)
#Sort the days of the week in the order of Monday → Sunday
heatmap_df = heatmap_df.rename(index=weekday_dic)
#Generate date df
date_df = data.loc[data.index.year == year,:].pivot(index='weekday',columns='week',values='date')
date_df = date_df.rename(index=weekday_dic)
#Add df to list
heatmap_df_lst.append([heatmap_df,np.array(date_df)])
return heatmap_df_lst
Run
gen_calmap(df=data,column_name_lst=['Electric energy[kWh]','Gas amount[m3]'],aggr='sum')
Recommended Posts