简体   繁体   English

在 x 轴上使用 plotly 直方图和时间 object

[英]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.不幸的是,我还没有找到答案,所以我来到了这个很棒的地方,在 stackoverflow 上提出了我的第一个问题。

What I want to do is the following: I have a dataframe that contains data over a period of 30 days.我想要做的是:我有一个 dataframe 包含 30 天的数据。 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.我想将 plot 每天的每日高点时间转换为 plotly 直方图,该直方图应在 x 轴上显示 0:00 到 23:59 范围内的时间。

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.但是,我无法格式化直方图的 x 轴范围,以正确显示一天中的时间并将每日最高点放入正确的 bin 中。 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.我找到了很多关于如何格式化 x 轴范围以在 x 轴上取日期的信息,但也找不到如何使用“简单”时间格式来做到这一点。

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)

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)我想我找到了一个解决方案,每次 object 需要与“假”日期相结合,并且通过一些格式化魔法它工作得很好(据我所知,在这个片段以及我的真实案例中)

Thanks a lot to https://stackoverflow.com/a/42030690/15378935非常感谢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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM