Search code examples
pythonplotlybubble-chart

Plotly: How to include multiple text variables in plot?


How can I show multiple text variables in an iplot()? Here is an example:

df2007.iplot(kind='bubble', x='gdpPercap', y='lifeExp', size='pop', text='country',
             xTitle='GDP per Capita', yTitle='Life Expectancy',
             filename='cufflinks/simple-bubble-chart')

taken from here: https://plot.ly/ipython-notebooks/cufflinks/#scatter-matrix

I want to add another variable to text, passing a list of column names doesn't help. I have tried

text = 'country' + <br/> + 'country'

Solution

  • In order to achieve this, you'll have to free yourself from the boundaries of px.Scatter. But you can use go.Scatter in combination with iplot() if that is what you prefer. The snippet below will show you how you can assign an extra variable with it's own data in your hovertext by formatting hovertemplate correctly and using the text propery of go.Scatter.

    Plot:

    enter image description here

    Complete code:

    import plotly.express as px
    from plotly.offline import iplot
    import plotly.graph_objects as go
    
    # data
    gapminder = px.data.gapminder()
    df=gapminder.query("year==2007").copy(deep=True)
    df['extraVar']=[i**4 for i in range(len(df))]
    
    # plotly
    fig=go.Figure()
    fig.add_trace(go.Scatter(x=df['gdpPercap'], y=df['lifeExp'],
                             mode='markers',
                             marker=dict(size=df['pop'],sizemode='area',
                                    sizeref=2.*max(df['pop'])/(40.**2),sizemin=2
                                        ),
                             hovertemplate =
                                            '<i>lifeExp</i>: $%{y:.2f}'+
                                            '<br><i>gdpPercap</i>: %{x}<br>'+
                                            '<i>%{text}</i>',
                             text = ['Your extra variable {}'.format(i) for i in df['extraVar']],
                            )
                 )
    
    # iplot
    iplot(fig)