Search code examples
python-3.xmatplotlibtreemapsquarify

Treemap - Change Fonts


So I have the following code that generates a tree map in Matplotlib. Wondering if it's possible to have the first line emboldened and a larger font size .

So:

Emboldened and larger: 0:

Smaller and no emboldening: 480

    import matplotlib.pyplot as plt
    import squarify    # pip install squarify (algorithm for treemap)
    import pandas as pd
    import psycopg2
    distributionlist = [480, 104, 55, 35, 29, 12, 18, 22, 14, 11, 144]
    group = ["0", "1", "2", "3", "4", "5", "6", "7","8","9","10+"]

    labels = ["%s:\n%s" % (label) for label in zip(group, distributionlist)]



    percents = [8,3,4,2,8,3,4,2]
    # Create a data frame with fake data
    df = pd.DataFrame({'nb_people': distributionlist, 'group':group })
    #df = pd.DataFrame({'nb_people':[8,3,4,2], 'group':["group A", "group B", "group C", "group D"] })

    # plot it

    squarify.plot(sizes=df['nb_people'], label=labels, alpha=.8)

    #squarify.plot(sizes=df['nb_people'], label=df['group'], alpha=.8 , color=colors )
    plt.axis('off')
    plt.show()

enter image description here


Solution

  • Usually a single matplotlib text only has one size and one style. Here the label is created as one string with a newline.

    You can use

    ax = squarify.plot(sizes=df['nb_people'], label=labels, alpha=.8)
    ax.texts[0].set_size(30)
    ax.texts[0].set_weight('bold')
    

    to set the text both larger and bold.

    To split the text and only set the weight of the first line:

    ax = squarify.plot(sizes=df['nb_people'], label=labels, alpha=.8)
    text_parts = ax.texts[0].get_text().split("\n")
    ax.texts[0].set_text(text_parts[0] + "\n")
    ax.texts[0].set_size(30)
    x, y = ax.texts[0].get_position()
    new_text = ax.text(x, y, "\n" + text_parts[1], ha=ax.texts[0].get_ha(), va=ax.texts[0].get_va())
    new_text.set_fontproperties(ax.texts[0].get_fontproperties())
    ax.texts[0].set_weight('bold')
    

    treemap with larger text