How to add vertical lines to a histogram in plotly dash?

Viewed 2254

I have a graph component that's is triggered upon a callback. Here's my code to plot a histogram from a callback function.

xtup = np.random.lognormal(90, 3, size=1000)
xtup = list(map('{:.0f}'.format,xtup[0]))
xarr = np.asarray(xtup).astype(np.float)

data = [go.Histogram(
                     x = xarr,
                     nbinsx=50,
                     marker=dict(color="rgb(105,105,105)",
                                 opacity=0.5
                                ),

       )]

layout = {
            "xaxis": {'title': 'Values',
                      'tickformat': '${:,.0f}'
                      #'range': [xarr.min(), xarr.max()]
                     },
            "title": "Distribution",
            "width": 650,
            "height": 400,
            "autosize": True
}

return{'data':data, 'layout':layout}

I'd like to add a dashed vertical line at the mean of the distribution.

1 Answers

Your code snippet isn't exactly easily reproducible, but building on this go.Histogram example, you can just include:

fig.add_vline(x=np.median(df.total_bill), line_dash = 'dash', line_color = 'firebrick')

And get:

enter image description here

Please note that add_vline will require a recent plotly version to function properly.

Complete code:

import plotly.express as px
import numpy as np
df = px.data.tips()
fig = px.histogram(df, x="total_bill")
fig.add_vline(x=np.median(df.total_bill), line_dash = 'dash', line_color = 'firebrick')
fig.show()
Related