Cannot change font for plots on the cloud

Hello all,

I am attempting to change the font on my graphs to Arial, and I am at my wits end trying to get it to work on the Community Cloud. It works just fine on my machine, but it returns “findfont: Font fa
mily ‘Arial’ not found.” when run on the cloud. My code that I am using to set the font is as follows:

path = ‘ARIAL.TTF’
prop = fm.FontProperties(fname=path)
plt.rcParams[‘font.family’] = prop.get_name()

The font is in the same folder as my script, and I have confirmed that it is the correct font, file format, etc. Any help you could provide would be greatly appreciated

Other requested information:

  1. https://p2f-hydratecalc.streamlit.app/
  2. GitHub - karstenkunneman/Gas-Hydrate-Equilibrium-Calculator
  3. Python 3.9.23, streamlit==1.40.1

Local files are not available to your frontend automatically. If you want a font file made available to a user’s browser, you’ll need to explicitly host it. You can use static file serving, and then access the files relative to your app’s URL.

You might want to look at Streamlit’s configuration options to make fonts available to your app, so that you can just access them by family name. There is a built-in way to incorporate @font-face declarations with your app.

Oh. I see you’re generating the plots as images and then serving them, so the font is processed on the server, not the frontend. What I said about hosting the font on the frontend doesn’t apply then. Sorry about that. (You can still host the font if you want to use it elsewhere in your app, though.)

I tried this with a Quicksand font and it worked. (I used a static hosted font, but these commands within Matplotlib are all run on the server and using the paths relative to the working directory, so the font file shouldn’t need to be in the static folder for this example.)

import streamlit as st
import numpy as np
from matplotlib import font_manager as fmgr, rcParams
import matplotlib.pyplot as plt

QuicksandPath = "static/Quicksand-VariableFont_wght.ttf" # Any path relative to your working directory
fmgr.fontManager.addfont(QuicksandPath)
fprop = fmgr.FontProperties(fname=QuicksandPath)
fname = fprop.get_name()
rcParams["font.family"] = fname

arr = np.random.normal(1, 1, size=100)
fig, ax = plt.subplots()
ax.hist(arr, bins=20)
ax.set_title("Title")

st.pyplot(fig)

Note: In practice, it’d probably be better to load the font just once instead of on every script rerun, so you could create an init=True flag in Session State to make sure you just run this at startup for the session. I just did a quick test and I think running the settings once in one session will impact all sessions, so just be aware. :slight_smile:

1 Like

Thank you so much! Apologies for the lack of clarity.