Search code examples
pythonpandasplotlystreamlit

Why is streamlit messing up my Plotly chart?


Importing the streamlit library into my Python code has changed my Plotly chart into black and white. The same description can also be found on the Plotly github page.

My problem can be replicated with the following steps:

First of all, I have the following system configuration:

Streamlit version: 1.23.1
Plotly version: 5.15
Python version: 3.11
Operating System: Windows 11 Pro (64-bit)
Browser: Microsoft Edge Version 114.0.1823.58 (64-bit)
Virtual environment: miniconda 23.3.1

Step 1. Setup a new environment at the command prompt

conda create -n test python==3.11
conda activate test
pip install numpy pandas plotly==5.15 streamlit==1.23.1

Step 2. Launch Python at the command prompt

python

**Step 3. Create a Plotly chart without importing the streamlit library by running these code **

import plotly.graph_objects as go
import numpy as np

t = np.linspace(0, 10, 100)
y = np.sin(t)
fig = go.Figure(go.Scatter(x=t, y=y, mode='markers'))
fig.show()

Step 4: My Plotly plot looks like this (expected behavior) enter image description here

Step 5: Import the streamlit library and re-run the same code.

import streamlit as st
import plotly.graph_objects as go
import numpy as np

t = np.linspace(0, 10, 100)
y = np.sin(t)
fig = go.Figure(go.Scatter(x=t, y=y, mode='markers'))
fig.show()

Step 6: My plotly chart becomes black and white like this (unexpected behavior) enter image description here

Step 7: It also affected Pandas's plot with plotly backend

import streamlit as st
import pandas as pd
pd.options.plotting.backend='plotly'

df = pd.DataFrame(np.random.random((10,10)))
fig = df.plot()
fig.show()

enter image description here

Does anyone know how to fix this issue?


Solution

  • This temporary solution works. Hopefully streamlit could find the permanent solution in the future.

    import streamlit as st
    ...
    ...
    # reset Plotly theme after streamlit import
    import plotly.io as pio
    pio.templates.default = 'plotly'