1

I would like to use 2 different font size in the same legend in a matplotlib graph.

For exemple, I would like to use a 15 points bold font for some labels and 10 points normal font for the others labels in the same legend box.

My plot legend already regroup legend from 2 axes (Single legend for multiple axes) and have a variable number of data plotted.

I already use blank data strategy to add annotation to the legend plot (Is it possible to add a string as a legend item in matplotlib). But I would like to make it with a bigger sized, bolt fount if it's possible.

Thank you!

Community
  • 1
  • 1

1 Answers1

0

You may be able to use the following pattern on the Text objects contained in the legend() :

leg = plt.legend()

for i, text in enumerate(leg.get_texts()):

    # pretend the element to be changed is in index position 3
    if i == 3: 
        text.set_weight("bold")
        text.set_size("x-large")

        # or equivalently with one call to setp()
        plt.setp(text, weight="bold", size="x-large")

EDIT: Looks like changing things in one text object inside a legend actually applies to all objects. One workaround that works is to use mathtext like so text.set_text(r'$\mathbf{label}$'). In the loop, we'd need to retrieve the label and deal with mathtext "condensing" the spaces. Here's an example:

line1, = plt.plot([3,2,1], marker='o', label='Line 1 label is long and has spaces')
line2, = plt.plot([1,2,3], marker='o', label='Line 2')
leg = plt.legend()

for i, text in enumerate(leg.get_texts()):

    # the element to be changed is in index position 0
    if i == 0: 
        t = text.get_text()
        new_label = "".join([i + r"\/" for i in t.split()])
        text.set_text(r'$\mathbf{}$'.format("{" + new_label + "}"))

I don't know if using mathtext or latex is acceptable to you, but it appears to allow unique formatting of a single legend text label.

aorr
  • 937
  • 7
  • 9
  • It didn't work for me. It change the properties of all legend text at the same time. Look like it can't handle different legend text font properties in the same legend. I tried too: for i, text in enumerate(leg.get_texts()): # pretend the element to be changed is in index position 3 print i if i == 0: text.set_weight("bold") text.set_size("x-large") else: text.set_weight("medium") text.set_size("x-small") But legend text will be all "medium" "x-small" of whatever the last item condition dictate. – Martial Lavoie May 12 '17 at 18:45
  • Hm, you're right. It doesn't look like the `text` instances inside a `legend` are really first-class citizens. However, I was able to adjust the fontweight using [mathtext](https://matplotlib.org/users/mathtext.html#custom-fonts), see edited answer. – aorr May 16 '17 at 20:52
  • i meant "are **not** really first-class citizens" – aorr May 16 '17 at 21:01