how to add a legend above a curve matploitlib in python

To add a legend above a curve in matplotlib, you can use the legend function with the loc parameter. The loc parameter specifies the location of the legend. Here's an example code snippet:

main.py
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [1, 4, 9, 16]

plt.plot(x, y)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Title')

plt.legend(['curve label'], loc='upper center', bbox_to_anchor=(0.5, 1.15))

plt.show()
246 chars
14 lines

In the plt.legend function call, the first parameter is a list of strings that correspond to the labels for each curve you're plotting. In this case, there's only one curve, so there's only one label. The loc parameter specifies the location of the legend. In this case, it's set to upper center. Finally, the bbox_to_anchor parameter sets the position of the legend relative to the plot. In this case, it's positioned above the plot at the center.

related categories

gistlibby LogSnag