Black Lives Matter. Please consider donating to Black Girls Code today.

Create bar between start and end time on chart

I have these results using jupyter notebook / pandas / plotly –

These refer to start and end times of a person working on days throughout the month of July.

Instead of two points on each end, what I’d really like are bars… ideally something like this (which I made on adobe illustrator)… any help?

My code looks like this:

trace_start = go.Scatter(
x=df.date,
y=df[‘stime’],
mode=‘markers’,
name = “start time”,
line = dict(color = ‘green’),
opacity = 0.8)

trace_end = go.Scatter(
x=df.date,
y=df[‘etime’],
mode=‘markers’,
name = “end time”,
line = dict(color = ‘red’),
opacity = 0.8)

data = [trace_start,trace_end]

layout = dict(
title = “Time Worked”,
xaxis = dict(
range = [‘2018-07-01’,‘2018-07-31’])
)

fig = dict(data=data, layout=layout)
py.iplot(fig, filename = ‘Time Worked’)

Hi @pjford,

You can use the base property of the bar trace to control the starting height of bars in a bar chart. For example:

import pandas as pd
import plotly.graph_objs as go
fig = go.FigureWidget()

dates = pd.date_range('2018-01', '2018-12', freq='MS')
fig.add_bar(x=dates,
            y=[2, 3, 4, 1, 4, 5, 3, 4, 5, 3, 2, 3],
            base=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
fig

Note that in this case y is not the top edge of the bar, but the height above the bar’s base

Hope that helps!
-Jon

This in theory seems like it would be a good solution, but when I run the sample code you’ve provided it runs forever and I have to restart jupyter notebook because it never finishes… any thoughts on what’s happening?

Hmm, no I don’t have any ideas.

Maybe something is going wrong for you with FigureWidget. Try displaying with iplot like you were originally:

import pandas as pd
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode()

fig = go.Figure()

dates = pd.date_range('2018-01', '2018-12', freq='MS')
fig.add_bar(x=dates,
            y=[2, 3, 4, 1, 4, 5, 3, 4, 5, 3, 2, 3],
            base=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
iplot(fig)

Thank you so much! I was able to get your example running. I changed the format a bit to make it about time… and came up with this below.

I’m still doing something wrong as there are these problems:

  1. The duration/bar-length is incorrect
  2. The X-axis is not showing the Jul-4 entry
  3. The Y-axis appears to be out of order… 8am, 730am, 815am…
  4. The Y-axis does not go far enough up

import pandas as pd
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode()

fig = go.Figure()

btime = pd.to_datetime(['2018-07-02 08:00','2018-07-03 07:30','2018-07-04 08:15'])

timedur = [pd.Timedelta('8 hours'),pd.Timedelta('8.25 hours'),pd.Timedelta('7.75 hours')]

thedates = pd.date_range('2017-07', '2017-08', freq='D')


fig.add_bar(x=thedates,

            y=timedur,

            base=btime)

iplot(fig)