I want to represent time_spent as combination of hours and minutes instead of bare seconds. I tried making HoursAndMinutes column and then adding it as y axis into graph, but that ruined scalling of bars. I want to be able to see time in format of (example) 5h 15min and also be able to scale bars properly. Maybe is it possible to sort by different column (time_spent) and display formatted version?
My code:
main.py
import pandas as pd
import plotly.express as px
from utils import TimeHandler
example_data = {"date": ["29/07/2022", "30/07/2022", "31/07/2022"],
"time_spent" : [15840, 21720, 40020]}
df = pd.DataFrame(example_data)
df["date"] = pd.to_datetime(df["date"], dayfirst=True)
for i, time_scale in enumerate(["hours", "minutes"]):
df[time_scale] = df.apply(lambda row: TimeHandler.unpack_seconds(row.time_spent)[i], axis=1)
df["HoursAndMinutes"] = df.apply(lambda row: f'{row.hours}h {row.minutes}min', axis=1)
fig = px.bar(df, x='date', y='HoursAndMinutes',
labels={'date':'Date'},
height=900)
config = {'displayModeBar': False}
fig.update_layout(
title='Time spent over days',
font={'size': 18})
fig.show(config=config)
utils.py
class TimeHandler:
@staticmethod
def unpack_seconds(seconds):
seconds = int(seconds)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
return hours, minutes, seconds
Current result chart:
Wanna get like this: