Graphing date vs time on plotly

被刻印的时光 ゝ 提交于 2019-12-10 10:37:13

问题


I have several data sets I would like to plot with dates as X axis and times as Y axis. I am working in Jupyter Notebook.

from datetime import date, time
from plotly import offline as py
from plotly.graph_objs import Scatter, Data
py.init_notebook_mode(connected=True)

meetings = Scatter(
    x=[date(2017, 1, 1), date(2017, 1, 3), date(2017, 1, 3)],
    y=[time(8, 0, 0), time(12, 0, 0), time(16, 0, 0)],
    text=['work meeting 1', 'work meeting 1', 'work meeting 1'],
    mode='markers'
)

workouts = Scatter(
    x=[date(2017, 1, 1), date(2017, 1, 2), date(2017, 1, 2)],
    y=[time(7, 30, 0), time(14, 30, 0), time(17, 0, 0)],
    text=['workout 1', 'workout 2', 'workout 3'],
    mode='markers'
)

data = Data([meetings, workouts])
py.iplot(data)

The result I get is this: The X axis includes time as well, and the Y axis goes in order of inserted data, not from bottom to top. Nothing I've tried with modifying the range/domain has fixed this. From what I've seen on the help page time objects aren't supported. Is there any way to make this type of plot work?


回答1:


In order to plot hours you would need to do two things:

  • Set the yaxis type to date and the tickformat to %H:%M
  • Convert your time objects to datetime objects

We just pretend everything on the yaxis happened on the same day but we only report the hour.

import plotly
import datetime as dt

meetings = plotly.graph_objs.Scatter(
    x=[dt.date(2017, 1, 1), dt.date(2017, 1, 3), dt.date(2017, 1, 3)],
    y=[dt.time(8, 0, 0), dt.time(12, 0, 0), dt.time(16, 0, 0)],
    text=['work meeting 1', 'work meeting 1', 'work meeting 1'],
    mode='markers'
)

workouts = plotly.graph_objs.Scatter(
    x=[dt.date(2017, 1, 1), dt.date(2017, 1, 2), dt.date(2017, 1, 2)],
    y=[dt.time(7, 30, 0), dt.time(14, 30, 0), dt.time(17, 0, 0)],
    text=['workout 1', 'workout 2', 'workout 3'],
    mode='markers'
)

for d in [meetings, workouts]:
    for i, t in enumerate(d.y):
        d.y[i] = dt.datetime.combine(dt.date(2017, 1, 1), t)

layout = plotly.graph_objs.Layout(yaxis={
    'type': 'date',
    'tickformat': '%H:%M'
    }
)

fig = plotly.graph_objs.Figure(
    data=plotly.graph_objs.Data([meetings, workouts]),
    layout=layout
)
plotly.offline.plot(fig)


来源:https://stackoverflow.com/questions/42027819/graphing-date-vs-time-on-plotly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!