pythonvisualizationtreemapsquarify

How do you make the font size of Squarify label proportionate to the size of the square?


I'm trying to make a treemap with squarify with some squares much bigger than the others.

title counts labels
A 100 A - 100
B 30 B - 30
C 25 C - 25
D 2 D - 2
E 2 E - 2
F 2 F - 2
G 2 G - 2
        fig, ax = plt.subplots(1, figsize = (12,12))
        ax = squarify.plot(sizes=df['counts'], 
                           label=df['labels'],
                           alpha=0.5)
        plt.axis('off')
        plt.show()

Is there a way to make the font size of A as big as its square size, font B smaller than A, font C a bit smaller than B, and the rest very small?

I found a parameter:

text_kwargs={'fontsize':10}

But it doesn't allow me to insert a list of sizes.


Solution

  • Maybe here can give you some hints to solve your problem.

    Recently I have created a matplotlib-extra project, which includes some extra functions to matplotlib. Currently it has a treemap and an AutoFitText class. The treemap supports the hierarchical treemap.

    For your case, it will be simple:

    import mpl_extra.treemap as tr
    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame({'title':list('ABCDEFG'), 
                       'counts':[100, 30, 25, 2, 2, 2, 2]})
    df['labels'] = [f'{a} - {b}' for a,b in zip(df['title'], df['counts'])]
    
    fig, ax = plt.subplots(figsize=(7,7), dpi=100, subplot_kw=dict(aspect=1.156))
    
    tr.treemap(ax, df, area='counts', labels='labels', 
               cmap='Set2', fill='title',
               rectprops=dict(ec='w'),
               textprops=dict(c='w'))
    
    ax.axis('off')
    

    It gives the following treemap:

    enter image description here