How to change fontsize of individual legend entries in pyplot?

2024/10/2 18:24:20

What I'm trying to do is control the fontsize of individual entries in a legend in pyplot. That is, I want the first entry to be one size, and the second entry to be another. This was my attempt at a solution, which does not work.

import numpy as np
import matplotlib.pyplot as pltx = np.arange(1,5,0.5)
plt.figure(1)
plt.plot(x,x,label='Curve 1')
plt.plot(x,2*x,label='Curve 2')
leg = plt.legend(loc = 0, fontsize = 'small')
leg.get_texts()[0].set_fontsize('medium')
plt.show()

My expectation is that the default size for all legend entries would 'small'. I then get a list of the Text objects, and change the fontsize for only a single Text object to medium. However, for some reason this changes all Text object fontsizes to medium, rather than just the single one I actually changed. I find this odd since I can individually set other properties such as text color in this manner.

Ultimately, I just need some way to change an individual entry's fontsize for a legend.

Answer

It appears that the font of each legend entry is managed by an instance of matplotlib.font_manager.FontProperties. The thing is: each entry doesn't have its own FontProperties... they all share the same one. This is verified by writing:

>>> t1, t2 = leg.get_texts()
>>> t1.get_fontproperties() is t2.get_fontproperties()
True

So if you change the size of the first entry, the size of the second entry is automatically changed along with it.

The "hack" to get around this is to simply create a distinct instance of FontProperties for each legend entry:

x = np.arange(1,5,0.5)
plt.figure(1)
plt.plot(x,x,label='Curve 1')
plt.plot(x,2*x,label='Curve 2')
leg = plt.legend(loc = 0, fontsize = 'small')t1, t2 = leg.get_texts()
# here we create the distinct instance
t1._fontproperties = t2._fontproperties.copy()
t1.set_size('medium')plt.show()

And now the sizing is correct:

enter image description here

https://en.xdnf.cn/q/70823.html

Related Q&A

Split array into equal sized windows [duplicate]

This question already has answers here:Sliding window of M-by-N shape numpy.ndarray(8 answers)Closed 10 months ago.I am trying to split an numpy.array of length 40 into smaller, equal-sized numpy.array…

Is there a way to send a click event to a window in the background in python?

So Im trying to build a bot to automate some actions in a mobile game that Im running on my pc through Bluestacks.My program takes a screenshot of the window, looks for certain button templates in the …

how to store an image into redis using python / PIL

Im using python and the Image module(PIL) to process images.I want to store the raw bits stream of the image object to redis so that others can directly read the images from redis using nginx & htt…

Delete OCR word from Image (OpenCV,Python)

So, from what I can begin..I am working with OCR. The script works pretty well for what I need. It detects the words with an accuracy which for me is ok.This is the result: 100% accuracy with attached …

pandas.to_datetime inconsistent time string format

I am attempting to convert the index of a pandas.DataFrame from string format to a datetime index, using pandas.to_datetime().Import pandas:In [1]: import pandas as pdIn [2]: pd.__version__ Out[2]: 0.1…

Python NLTK WUP Similarity Score not unity for exact same word

Simple code like follows gives out similarity score of 0.75 for both cases. As you can see both the words are the exact same. To avoid any confusion I also compared a word with itself. The score refuse…

SystemExit: 2 error when calling parse_args() in iPython Notebook

Im learning to use Python and scikit-learn and executed the following block of codes (originally from http://scikit-learn.org/stable/auto_examples/document_classification_20newsgroups.html#example-docu…

How to convert numpy datetime64 [ns] to python datetime?

I need to convert dates from pandas frame values in the separate function:def myfunc(lat, lon, when):ts = (when - np.datetime64(1970-01-01T00:00:00Z,s)) / np.timedelta64(1, s)date = datetime.datetime.u…

how to remove a back slash from a JSON file

I want to create a json file like this:{"946705035":4,"946706692":4 ...}I am taking a column that only contains Unix Timestamp and group them.result = data[Last_Modified_Date_unixti…

Can sockets be used to connect multiple computers on different networks in python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 6…