pythonmatplotlibplotnine

Change the font name of exponent labels in plotnine/matplotlib


I am trying to make a plot using plotnine. The y-axis is in log-scale and has an exponential labels. I want to change the font of the whole plot to something else such as "Gill Sans". The font is reflected everywhere except the exponential labels. How to fix that? Below is a working example.

import plotnine as p9
import pandas as pd
import mizani

data = {
    "Degree": [3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6],
    "Probability": [0.00001, 0.00002, 0.00003, 0.001, 0.002, 0.003, 0.01, 0.02, 0.03, 0.1, 0.2, 0.3],
    "p": ["p=0.01", "p=0.01", "p=0.01", "p=0.1", "p=0.1", "p=0.1", "p=0.01", "p=0.01", "p=0.01", "p=0.1", "p=0.1", "p=0.1"],
    "Scheme": ["Theoretical", "Original", "Proposed", "Theoretical", "Original", "Proposed", "Theoretical", "Original", "Proposed", "Theoretical", "Original", "Proposed"],
}

df = pd.DataFrame(data)

x_val = "Degree"
y_val = "Probability"
y_label = "Degree Probability"
g1_val = "p"
g2_val = "Scheme"

p = (
    p9.ggplot(df)
    + p9.aes(x=x_val, y=y_val, color=g1_val, shape=g2_val, linetype=g2_val, size=g2_val)
    + p9.geom_point(alpha=0.8)
    + p9.geom_line(size=0.5)
    + p9.scale_x_continuous(name=x_val, breaks=[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
    + p9.scale_y_continuous(name=y_label, trans=mizani.transforms.log_trans(10), labels=mizani.labels.label_log(mathtex=True))
    + p9.geom_vline(xintercept=6, size=0.4, linetype="dotted", color="black")
    + p9.geom_vline(xintercept=3, size=0.4, linetype="dotted", color="black")
    + p9.scale_shape_manual(name="Algorithm", values=["o", "*", "+"])
    + p9.scale_color_manual(name="Rewiring Prob.", values=["red", "blue"])
    + p9.scale_linetype_manual(name="Algorithm", values=["none", "none", "solid"])
    + p9.scale_size_manual(name="Algorithm", values=[5, 5, 2])
    + p9.theme(text=p9.element_text(family="Gill Sans", weight="regular"))
)

p

Output


Solution

  • Ok, finally figured this out. I can use the following code to set the font.

    import matplotlib.pyplot as plt
    plt.rcParams['mathtext.fontset'] = 'custom'
    plt.rcParams['mathtext.rm'] = 'Gill Sans'