Plotly express histogram, print count values in hover over

Hi Plotly Wizards!
I am trying to make a plotly.express.histogram with histnorm="percent" to show count of observations in hover over tooltip instead of percent. Any tips?

This is what you get with the following code, I just want count instead of percent.

   fig = px.histogram(
        data,
        x=value_column,
        color=group_by_column,
        barmode="overlay",
        histnorm="percent",
        # also creates a boxplot
        marginal="box",
        labels=labels,
    )

The doc for modifying hover text appearance is at the link below.

If you need a more specific answer, is there any chance you could post a self-contained example (with some data) that can be modified?

1 Like

Thanks for the response! I did look into to the hover text documentation before posting here, but it didn’t seem to work for my specific case. Here is a minimal self contained example:

import plotly.express as px
from scipy.stats import norm, t

N1 = 1000
N2 = 1000
QUANTILE = 0.99
DF = 3

np.random.seed(1)
y_1 = norm.rvs(size=N1)
y_2 = t.rvs(DF, size=N2)
metrics_df = pd.DataFrame(
  {
    "x": np.concatenate([y_1, y_2]),
    "distribution": ["normal"]*N1 + ["student"]*N2
  }
)

px.histogram(
        metrics_df,
        x="x",
        color="distribution",
        barmode="overlay",
        histnorm="percent",
        marginal="box",
    )

The hover text shows percent for given bin. I would like it to show count while keeping the y axis as percent.

Apologies, I see your problem. As far as I know the only way to dig into this sort of thing is to wrap a figure in a small Dash app, create a callback for β€˜hoverData’, and examine what gets returned, which is the same as the data that can be shown on hover.

It turns out for px.histogram() there is only one y value available, which is a percentage if you use histnorm=β€œpercent” and a count if you don’t, so it looks like the hover data is linked to the y axis display. One way to get around this might be to display counts in the histogram, and then to modify the tick labels on the y axis so they show percentage values. Another might be to calculate the histogram values in code and then display them using px.Bar(), which should allow customdata to be passed and then shown in the hover display.

2 Likes