1

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

dipl0
  • 1,017
  • 2
  • 13
  • 36

1 Answers1

3

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

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • That's really cool thanks, is there any way I can do it across all of the different values in the treemap ? – dipl0 Mar 18 '21 at 20:52
  • 1
    Well, you can loop through `ax.texts`. Just be careful that the sample code creates additional texts that you don't want to loop through. – JohanC Mar 18 '21 at 20:57
  • 1
    You can also use latex format as in [Make part of a matplotlib title bold and a different color](https://stackoverflow.com/questions/34937048/make-part-of-a-matplotlib-title-bold-and-a-different-color) – JohanC Mar 18 '21 at 21:00