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

Plotly Express: Line chart with Histogram

Hi everyone,

I was wondering if it is possible to overlay a line chart with histograms? As an example, the NY Fed Nowcasting charts: https://www.newyorkfed.org/research/policy/nowcast.html

I have two use cases:

  1. (With Secondary y-axis) I have a stock price time series I would like to plot. Then have a secondary y-axis that shows the Stock returns (current price / previous price - 1) as histograms. E.g. https://finance.yahoo.com/quote/AAPL/history?period1=1557217824&period2=1588840224&interval=1wk&filter=history&frequency=1wk

  2. (Same y-axis) Like the NY Fed chart, I have level values and underlying components. I would like to show the level as a line chart and the underlying components as stacked histograms. Since the components add up to the level value, have the histogram share the same y-axis would be ideal.

I know how to make the two charts
As I am new to plotly, plus points if it is possible to do it with Plotly express! :slight_smile:

thanks in advance

Hi @hiqbal2 welcome to the forum! Yes you create a chart with both a scatter trace and a histogram trace. Create an empty figure then use fig.add_trace to add the two traces

import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Histogram(x=[1, 2, 0, 2, 1, 0, 2]))
fig.add_trace(go.Scatter(x=[0, 1, 2], y=[1, 3, 2], mode='lines'))
fig.show()

you can also create the first trace with plotly express and call fig.add_trace on the figure returned by px to add the second trace.
You can read https://plotly.com/python/creating-and-updating-figures/ for more about fig.add_trace. About the secondary y-axis, the tutorial on multiple axes has several examples.