Photo by Bill White: https://www.pexels.com/photo/green-forest-under-white-sky-during-daytime-165537/
To add a custom legend in Matplotlib, you can use the
legendfunction, which allows you to create a legend for your plot.
Here's an example of how to create a custom legend:
pythonimport matplotlib.pyplot as plt # Create some data to plot x = [1, 2, 3, 4] y1 = [1, 2, 3, 4] y2 = [2, 4, 6, 8] # Plot the data plt.plot(x, y1, label='Line 1') plt.plot(x, y2, label='Line 2') # Create a custom legend custom_legend = plt.legend(['Line 1', 'Line 2'], loc='upper left') # Add the custom legend to the plot plt.gca().add_artist(custom_legend) # Show the plot plt.show()
In this example, we first plot two lines with labels 'Line 1' and 'Line 2'. Then, we create a custom legend by passing a list of strings representing the labels and specifying the location of the legend. Finally, we add the custom legend to the plot using the
add_artist method of the current axes object.
Post a Comment