How to add a title to a Matplotlib legend?

How to add a title to a Matplotlib legend?

In Matplotlib, you can add a title to a legend using the set_title method of the Legend object. Here's how you can add a title to a legend:

Example:

import matplotlib.pyplot as plt import numpy as np # Generate some sample data x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) # Plot the data plt.plot(x, y1, label="sin(x)") plt.plot(x, y2, label="cos(x)") # Add legend with title legend = plt.legend(loc="upper right") legend.set_title("Functions") plt.show() 

In the above code:

  1. We plot two functions: sin(x) and cos(x).
  2. We then call plt.legend() to create the legend and specify its location with the loc argument.
  3. We use the set_title method of the Legend object to set the title of the legend.

The resulting plot will display a legend with the title "Functions" and two legend entries corresponding to the two plotted functions.


More Tags

multiple-results instanceof poster spfx worksheet javascript-1.7 primes r-factor maya jsdom

More Programming Guides

Other Guides

More Programming Examples