Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsive text in Matplotlib in Python

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!!!

like image 527
Ivan Ivanov Avatar asked Sep 19 '25 12:09

Ivan Ivanov


1 Answers

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()
like image 121
ImportanceOfBeingErnest Avatar answered Sep 21 '25 05:09

ImportanceOfBeingErnest