user13255600
user13255600

Reputation: 27

How to add a Histogram to a time series or line chart chart in Plotly

I have no issues display the time series component, however, I cant seem to be able to add the histogram section into the display. I have attached the issue below. The time series with my slider displays how I want it however the histogram is nowhere to be seen. Any help will be appreciated.

fig = px.line(df, x='OPR_DATE', y='HERMISTON_GENERATING', title='Daily Flow for Hermiston', template = "simple_white")

# Issue Seems to be in here
fig.add_trace(go.Histogram(
    x=Herm['Total'],
    histnorm='percent',
    name='Contracted', # name used in legend and hover labels
    xbins=dict( # bins used for histogram
        start=-4.0,
        end=3.0,
        size=0.5
    ),
    marker_color='#EB89B5',
    opacity=0.75
))

fig.update_xaxes(
    rangeslider_visible=True,
    rangeselector=dict(
        buttons=list([
            dict(count=1, label="1m", step="month", stepmode="backward"),
            dict(count=6, label="6m", step="month", stepmode="backward"),
            dict(count=1, label="YTD", step="year", stepmode="todate"),
            dict(count=1, label="1y", step="year", stepmode="backward"),
            dict(step="all")
        ])
    )
)
fig.update_layout(
    title_text='Daily Flow for Hermiston + Contracted Volumes', # title of plot
    xaxis_title_text='OPR_DATE', # xaxis label
    yaxis_title_text='Daily Flows', # yaxis label
    bargap=0.2, # gap between bars of adjacent location coordinates
    bargroupgap=0.1 # gap between bars of the same location coordinates
)
fig.show()

Upvotes: 1

Views: 711

Answers (1)

jayveesea
jayveesea

Reputation: 3219

I believe you will want these in separate plots or subplots. Using the latter you could do the following:

Bring in the libraries and some sample data

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
import pandas as pd

# some sample data
N=250
df = pd.DataFrame({'OPR_DATE': np.arange(0, N)+np.datetime64('2018-05-01'),
                   'HERMISTON_GENERATING': np.random.randint(0,1000,N),
                   'VOLUME': np.random.uniform(-3,3,N)})

Create a subplot and add the line and histogram

# now setup the subplot
fig = make_subplots(
    rows=2, cols=1,
    subplot_titles=("Daily Flow for Hermiston", "Contracted Volumes"),
    row_heights=[0.5, 0.5],
    specs=[[{"type": "xy"}], [{"type": "bar"}]])

# add the line
fig.add_trace(go.Scatter(x=df['OPR_DATE'],
                         y=df['HERMISTON_GENERATING']),
              row=1, col=1) #note the row/col

# add the histogram
fig.add_trace(go.Histogram(
        x=df['VOLUME'],
        histnorm='percent',
        name='Contracted',
        xbins=dict(start=-4.0, end=3.0, size=0.5),
        marker_color='#EB89B5',
        opacity=0.75),
    row=2, col=1) #note the row/col

Update the figures

# update the line plot's x-axis
fig.update_xaxes(row=1, col=1, #note the row/col
                 title_text="OPR_DATE",
                 rangeslider_visible=True,
                 rangeslider_thickness=0.05,
                 rangeselector=dict(
                 buttons=list([
                    dict(count=1, label="1m", step="month", stepmode="backward"),
                    dict(count=6, label="6m", step="month", stepmode="backward"),
                    dict(count=1, label="YTD", step="year", stepmode="todate"),
                    dict(count=1, label="1y", step="year", stepmode="backward"),
                    dict(step="all")])))

# update the other axes with titles
fig.update_yaxes(title_text="Daily Flows", row=1, col=1) #note the row/col
fig.update_xaxes(title_text="VOLUME", row=2, col=1) #note the row/col
fig.update_yaxes(title_text="PCT", row=2, col=1) #note the row/col

# update the whole thing
fig.update_layout(
    title_text='Daily Flow for Hermiston + Contracted Volumes',
    showlegend=False, # not useful here
    bargap=0.2, width=900, height=900,
)
fig.show()

enter image description here

Upvotes: 1

Related Questions