Gernot
Gernot

Reputation: 21

Use plotly Histogram with time object on x-axis

there is an issue that has been bugging me for the last two days. Unfortunately I couldn't find an answer to it yet, leading me to this wonderful place to ask my first question on stackoverflow.

What I want to do is the following: I have a dataframe that contains data over a period of 30 days. In each day, a daily high is reached at a certain time. I want to plot the time of this daily high for each day into a plotly Histogram, which should display times in a range from 0:00 to 23:59 on the x-axis.

However, I am unable to format the x-axis range of the Histogram in a way that properly displays the time of the day and puts the daily highs into the correct bins. I found a lot of information on how to format the x-axis range to take Dates on the x-axis, but couldn't find how to do that with a "simple" Time format as well.

Below is a snippet of code that hopefully serves as a suitable minimal example.

Thanks a lot!!

from plotly.offline import plot
import plotly.graph_objects as go
import datetime

x = [datetime.time(0,20,0),
     datetime.time(3,24,0),
     datetime.time(12,12,0)]

y = [1,1,1]

fig = go.Figure(data=[go.Histogram(x=x, y=y)])
# Set xaxis range --- Here's where things go wrong...
fig.update_layout(xaxis_range=[datetime.datetime(2013, 1, 1, 0, 0),
                               datetime.datetime(2013, 1, 1, 23, 59)])
plot(fig)

Upvotes: 0

Views: 4224

Answers (1)

Gernot
Gernot

Reputation: 21

I think I found a solution, each time object needs to be combined with a "fake" date, and with some formatting magic it works out fine (both on this snippet as well as on my real case, as far as I can tell)

Thanks a lot to https://stackoverflow.com/a/42030690/15378935

from plotly.offline import plot
import plotly.graph_objects as go
import datetime as dt 

x = [dt.time(0,20,0),
     dt.time(3,24,0),
     dt.time(12,12,0)]

y = [1,1,1]

for index, time in enumerate(x):
    x[index] = dt.datetime.combine(dt.date(2017, 1, 1), time)

fig = go.Figure(data=[go.Histogram(histfunc="sum", x=x, y=y, nbinsx=24*2)])
# Set xaxis range
fig.update_xaxes(type='date', 
                 tickformat='%H:%M', 
                 nticks=24*2, 
                 range=[dt.datetime(2017, 1, 1, 0, 0),dt.datetime(2017, 1, 1, 23, 59)])
plot(fig)

Upvotes: 2

Related Questions