tonton-golio / computational_physics

computational_physics
https://physics.streamlit.app/
MIT License
4 stars 1 forks source link

Theme aware rcparams #5

Open tonton-golio opened 1 year ago

tonton-golio commented 1 year ago

Can we read the theme from within our python script, and in turn set rcParams to match?

yoshiysoh commented 1 year ago

I've been working on this issue and I found this is quite heavy and challenging problem... I mean, this is more difficult than how it looks :(.

Here is my report on this problem. I hope this helps you guys.

What I have done so far

Searching on Google

I found the official document of the theme, which is not helpful for our purpose. We can understand how to make a custom theme but we never know how to automatically detect the theme.

Searching on community forum of Streamlit

I found two people who want to do the exactly same thing.

Searching on Issue of Streamlit GitHub

I have good news and bad news. The good news is, finally, I found something useful :). The bad news is that I realized that we cannot solve this problem easily :(.

I found two helpful posts.

Possible solutions I have (and imagine)

Using Plotly (cool)

Thankfully and mysteriously, st.plotly_chart can detect the theme. One possible suggestion is creating all new figures with Plotly. (However, as all of you know, I am a big fan of Matplotlib and I can implement what I want to do faster with it. Therefore, I continue to use my dearest Matplotlib XD)

I checked the source code but I cannot understand how it works. Absolutely, it has a connection with the frontend (you know graphs of Plotly is interactive which means they somehow get information from the frontend).

Only one mode (uncool)

I found the dark theme of Matplotlib. Thus, if we fix the theme of either "light or "dark", we can make sophisticated pages but when users change the theme the pages become not well-designed.

Waiting for a newer version of Streamlit (cool, cool, cool)

I guess, at some point, developers will implement some features to solve this problem. As you know, the development pace of Streamlit is fast, so we can fairly expect to solve this problem by just waiting ;).

Conclusion

yoshiysoh commented 1 year ago

I would like to add one more solution I recently noticed.

Using Matplotlib with a user-defined theme

As I mentioned before, there is a dark theme for Matplotlib. Depending on the user-defined theme, we can switch to the dark theme. I get a user-defined theme from st.radio and use an if sentence. An example is below.

    theme = st.radio("Choose theme", ("Light", "Dark"), horizontal=True)

    if theme=="Light":
        plt.rcdefaults()
    else:
        plt.style.use('dark_background')

By using this, we can avoid migrating from Matplotlib to Plotly. You know, it is too much to remake all figures we already have with Plotly.