在图表上绘制日期与时间的关系图

时间:2017-02-03 15:37:09

标签: python plot plotly

我想要绘制几个数据集,其中日期为X轴,时间为Y轴。我在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)

我得到的结果是: result X轴也包括时间,Y轴按插入数据的顺序排列,而不是从底部到顶部。我没有尝试修改范围/域已修复此问题。 从我在help page时看到的时间不支持对象。 有没有办法使这种类型的情节有效?

1 个答案:

答案 0 :(得分:6)

为了绘制小时,你需要做两件事:

  • 将yaxis type设置为日期,将tickformat设置为%H:%M
  • time个对象转换为datetime个对象

我们只假装yaxis上的所有东西都发生在同一天,但我们只报告时间。

enter image description here

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)