2
votes

I am trying with one of the example provided at https://plotly.com/python/horizontal-bar-charts/ under the section Colored Horizontal Bar Chart. But instead of number I am using dates

Code

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Bar(
    y=['giraffes', 'orangutans', 'monkeys'],
    x=['2012-02-02', '2012-02-01', '2012-02-01'],
    name='SF Zoo',
    orientation='h',
    marker=dict(
        color='rgba(246, 78, 139, 0.6)',
        line=dict(color='rgba(246, 78, 139, 1.0)', width=3)
    )
))
fig.add_trace(go.Bar(
    y=['giraffes', 'orangutans', 'monkeys'],
    x=['2012-02-10', '2012-02-06', '2012-02-28'],
    name='LA Zoo',
    orientation='h',
    marker=dict(
        color='rgba(58, 71, 80, 0.6)',
        line=dict(color='rgba(58, 71, 80, 1.0)', width=3)
    )
))

fig.update_layout(barmode='stack')
fig.show()

I tried with datetime.datetime(2012, 2, 2, 0, 0), still give me a completely wrong graph. I tried playing with the layout format but still couldn't fix this

Plot:

enter image description here

1
What kind of bar graph are you expecting? Do you want the date to be the height of each bar? - Derek O
Using a date as the height for each bar is problematic because telling plotly what 0 height means in terms of the date is confusing. You would probably need to use a workaround like for the parameter x, input a list with the number of days since the beginning of the month such as x=[2, 1, 1] or x=[10,6,28] and then add custom xlabels to the axis yourself - Derek O
@vestland I think it's a modified example from the Plotly documentation so what's being plotted is the dataset - Derek O
@DerekO You're right! I'm so used to seeing questions without data that I'm asking for it by default. - vestland
@DerekO o yeah you are right, that make sense, need a starting reference for date. I thought of number of days too but my dataset span across years. it would be very confusing to read. Is there no way to set a starting reference? I tried adding a range for x that didnt work - user1294510

1 Answers

0
votes

One solution is to use a Gantt Chart which may handle dates better (especially defining where it starts and ends).

Here's a working example:

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="LA Zoo", Start='2012-02-02', Finish='2012-02-10', Resource="giraffes"),
    dict(Task="LA Zoo", Start='2012-02-01', Finish='2012-02-6', Resource="orangutans"),
    dict(Task="LA Zoo", Start='2012-02-01', Finish='2012-02-28', Resource="monkeys"),
    dict(Task="SF Zoo", Start='2012-02-10', Finish='2012-02-17', Resource="giraffes"),
    dict(Task="SF Zoo", Start='2012-02-6', Finish='2012-02-22', Resource="orangutans"),
    dict(Task="SF Zoo", Start='2012-02-28', Finish='2012-03-07', Resource="monkeys")
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Resource", color="Task")
fig.show()

enter image description here