Plotly chart "'Figure' object is not callable error" when displaying it on Streamlit page

58 views Asked by At

I have an issue with using Plotly and Streamlit together. The chart I've created works fine if I execute the code separately. But once I put the figure in st.plotly_chart, I get the 'Figure' object is not callable error.

Here is the chart code:

import pandas as pd
import plotly.express as px

d = {'Country': ['Portugal', 'Singapore', 'Norway', 'Mexico'], 
     'Rank': [33, 32, 30, 29],
     'Documents': [9950, 10154, 10892, 11073],
     'Citations': [110328, 134823, 176569, 103293],
     'H.index': [297, 349, 402, 289]
     }
df = pd.DataFrame(data=d)

fig = px.scatter(x = pays_prod_moy['Citations'],
                  y = pays_prod_moy['Documents'],
                  size = pays_prod_moy['H.index'], 
                  color = pays_prod_moy['Rank'],
                  hover_name = pays_prod_moy['Country'], 
                  log_x=True, 
                  size_max=40,
                  color_continuous_scale='RdBu')
fig.update_layout(
    xaxis_title="Average Documents",
    yaxis_title="Average Citations",
    coloraxis_colorbar_title="Rank"
)
st.plotly_chart(fig, use_container_width=True)

I've seen that it can come from syntax, so I checked it but I have the same issue when I paste an example chart code from Plotly documentation. Both libraries have been just freshly installed. And it works with Altair charts.

Do you have any idea where does it come from and how to fix this?

1

There are 1 answers

0
UnicornOnAzur On

I've added import streamlit as st, renamed the dataframe to pays_prod_mod and it works.

Your code would be:

import pandas as pd
import plotly.express as px
import streamlit as st

d = {'Country': ['Portugal', 'Singapore', 'Norway', 'Mexico'],
     'Rank': [33, 32, 30, 29],
     'Documents': [9950, 10154, 10892, 11073],
     'Citations': [110328, 134823, 176569, 103293],
     'H.index': [297, 349, 402, 289]
     }
pays_prod_moy = pd.DataFrame(data=d)

fig = px.scatter(x = pays_prod_moy['Citations'],
                 y = pays_prod_moy['Documents'],
                 size = pays_prod_moy['H.index'],
                 color = pays_prod_moy['Rank'],
                 hover_name = pays_prod_moy['Country'],
                 log_x=True,
                 size_max=40,
                 color_continuous_scale='RdBu')
fig.update_layout(xaxis_title="Average Documents",
                  yaxis_title="Average Citations",
                  coloraxis_colorbar_title="Rank"
                 )
st.plotly_chart(fig, use_container_width=True)