4

I am developing a simple graph visualizer using networkX and Matplotlib in Python. I also have some buttons plotted with text in them. As a whole the design is responsive which means that the graph and the buttons scale when I resize the window. However, the text size remains the same which makes the whole visualizer look very bad when not resized enough. Do you know how I can make the text also responsive?

Thank you in advance!!!

1 Answer 1

5
+100

You update the fontsize of a matplotlib.text.Text using text.set_fontsize(). You can use a "resize_event" to call a function that sets a new fontsize. In order to do this with every text in a plot, it might be helpful to define a class that stores initial figure height and fontsizes and updates the fontsizes once the figure is resized, scaled by the new figure height divided by the initial one.

You may then also define a minimal readable fontsize, below which the text should not be resized.

A full example:

import matplotlib.pyplot as plt
import numpy as np

class TextResizer():
    def __init__(self, texts, fig=None, minimal=4):
        if not fig: fig = plt.gcf()
        self.fig=fig
        self.texts = texts
        self.fontsizes = [t.get_fontsize() for t in self.texts]
        _, self.windowheight = fig.get_size_inches()*fig.dpi
        self.minimal= minimal

    def __call__(self, event=None):
        scale = event.height / self.windowheight
        for i in range(len(self.texts)):
            newsize = np.max([int(self.fontsizes[i]*scale), self.minimal])
            self.texts[i].set_fontsize(newsize)

fontsize=11
text = plt.text(0.7, 0.6, "Some text", fontsize=fontsize,
                bbox={'facecolor':'skyblue', 'alpha':0.5, 'pad':10})

cid = plt.gcf().canvas.mpl_connect("resize_event", TextResizer([text]))

plt.show()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This is great. Just to let you know my motivation for the bounty on the question- I was trying to figure out good text size defaults, that are more like percentage of the plot area, than hardcoded. I wonder if something like this would exist as a default!
Default fontsize is 10 and default figure size is 4.8 inch. If you double the figure size, take a fontsize of 20 etc. Maybe you don't actually want to change the figure size, but the dpi?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.