绘制日期与时间的关系图 [英] Graphing date vs time on plotly

查看:240
本文介绍了绘制日期与时间的关系图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制一些数据集,其中日期作为X轴,时间作为Y轴.我正在使用Jupyter Notebook.

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)

我得到的结果是这样的: X轴也包括时间,Y轴按插入数据的顺序排列,而不是从下到上.我尝试修改范围/域的任何方法都无法解决此问题. 根据我在帮助页面中看到的时间对象不支持. 有什么方法可以使这种绘图工作?

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?

推荐答案

要绘制小时数,您需要做两件事:

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

  • 将yaxis type设置为日期,将tickformat设置为%H:%M
  • 将您的time对象转换为datetime对象
  • Set the yaxis type to date and the tickformat to %H:%M
  • Convert your time objects to datetime objects

我们只是假装y轴上的所有事情都是在同一天发生的,但我们只报告小时数.

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)

这篇关于绘制日期与时间的关系图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆