how to add a legend above a curve matploitlib in python plot in python

You can add a legend above a curve in a matplotlib plot in python by doing the following:

  1. Specify labels for each curve by passing a label parameter to the plt.plot() method:
main.py
plt.plot(x, y1, label="Curve 1")
plt.plot(x, y2, label="Curve 2")
66 chars
3 lines
  1. Enable the legend to be drawn by calling plt.legend() method.
main.py
plt.legend()
13 chars
2 lines
  1. Use the loc parameter of plt.legend() method to specify the location of the legend box.
main.py
plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.1), ncol=2)
66 chars
2 lines

Here, the loc parameter is set to upper center, bbox_to_anchor parameter is used to set the position of the legend box relative to the axes (in this case, it is positioned slightly above the top-center point of the plot) and finally ncol parameter is set to 2, to split the legend items into 2 columns. You can adjust these parameters to change the location and position of the legend box.

Here's the complete code:

main.py
import matplotlib.pyplot as plt

# data 
x = [2, 4, 6, 8]
y1 = [1, 3, 5, 7]
y2 = [2, 4, 6, 8]

# plot the curves with labels
plt.plot(x, y1, label="Curve 1")
plt.plot(x, y2, label="Curve 2")

# customize the legend location above the plot
plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.1), ncol=2)

# show the plot
plt.show()
333 chars
17 lines

This will display the plot with the legend box at the top center of the plot, as shown below: matplotlib-legend-above-curve

gistlibby LogSnag