[Python] Access variables available in plotly's default hovertemplate

Discussão em 'Python' iniciado por Stack, Maio 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to change the hovertemplate on a stacked bar chart with plotly, but I'm struggling to access the same variables that plotly does by default. Here's the MWE I'm working with

    import plotly.express as px
    import pandas as pd

    df = pd.DataFrame({
    'value': [3,4,5,6,7,8],
    'category': ['Cat 1', 'Cat 1', 'Cat 1', 'Cat 2', 'Cat 2', 'Cat 2'],
    'subplot': ['Eggs', 'Chips', 'Beans', 'Eggs', 'Chips', 'Beans']})

    fig = px.bar(df, x=df['subplot'], y=df['value'], color=df['category'])
    print("plotly express hovertemplate:", fig.data[0].hovertemplate)
    fig.update_traces(hovertemplate='%{category}%{value}%{subplot}%{x}%{y}%{label}%{color}%{text}')
    fig.show()


    Without editing the hovertemplate, plotly produces: category=Cat 1<br>Food item=%{x}<br>units of stuff=%{y}<extra></extra> but I can't see a way to edit that template and get access to the category variable. (Getting the value and the food-stuff works with a couple of the variables in my custom hovertemplate.)

    I tried every keyword I could think of (and some from the documentation here (I don't know why plotly's documentation links to the pie chart page)), but I can never get Cat 1 or Cat 2 to show up in my template.

    Continue reading...

Compartilhe esta Página