pythonpandasdataframeplotly

Python Plotly - customdata saving all columns at the first index and separating them by commas


Whenever I add more than one column to my customdata, it saves the data at the first index (customdata[0]) and separates them by commas, instead of spreading them out across different indexes. Any reference to the other indexes shows the literal text (ex. calling %{customdata[1]} will just show %{customdata[1]} itself.)

Also, whenever I try to format the data (ex. $%{customdata[0]:,.2f}) when customdata has multiple inputs, it turns the data into NaN.

How can I make sure the data gets spread to the other indexes? Is this even the correct approach/syntax to passing my data to the hover text?

Context: I'm making a donut chart with plotly express, and using Pandas to pass it data from my spreadsheet. I want to display additional information when I hover over each part of the graph by using hover text. I'm doing this by passing the spreadsheet's columns as customdata under the update_traces function, and referencing them in the hovertemplate.

    exceldf = pd.read_excel('spreadsheetname.xlsx', sheet_name='Transaction', usecols='B:H', skiprows=4)
    exceldf = exceldf.dropna(how='any')

    donutchart = px.pie(
        exceldf, 
        names='Ticker', 
        values='Weight', 
        hole=0.5,
    )
    
    donutchart.update_traces(
    customdata=exceldf[['Live Price', 'Purchase Price', 'Quantity']].to_numpy(),
    hovertemplate='Customdata[0]: %{customdata[0]}<br>Customdata[1]: %{customdata[1]}<br>Customdata[2]: %{customdata[2]}<extra></extra>'
    )

I've tried to correct this by: -Changing customdata to a numpy array (no change) -Checking whether the columns' data types were correct (these 3 are floats) -Using hover_data instead of hovertemplate (gives me an ambiguous input error)


Solution

  • Since your data is unknown, add multiple column names to custom_data in list form based on this reference example. Specify the location of that list for the hover template specification and add the numeric display format.

    import plotly.express as px
    df = px.data.gapminder().query("year == 2007").query("continent == 'Asia'")
    df = df.sort_values('pop', ascending=False).head(10)
    
    fig = px.pie(df,
                 values='pop',
                 names='country',
                 custom_data=['lifeExp', 'gdpPercap'],
                 title='Top 10 population of Asia continent',
                 hole=0.5,)
        
    fig.update_traces(
        hovertemplate=
        "LifeExp: %{customdata[0][0]:.02f}<br>" +
        "GDPperCap: %{customdata[0][1]:.02f}" +
        "<extra></extra>"
    )
    fig.show()
    

    enter image description here