matplotlib plot legedn in python

To add a legend box to a matplotlib plot, you can use the legend() function. The legend function takes several arguments like the position of the legend and the labels to display.

Here is an example:

main.py
import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [2, 4, 6, 8], label='Line A')
plt.plot([1, 2, 3, 4], [3, 6, 9, 12], label='Line B')

plt.legend(loc='upper right')
plt.show()
182 chars
8 lines

In this example, plt.legend(loc='upper right') adds a legend to the upper right corner of the plot.

You can also explicitly set the labels for each line in the legend by passing a list of labels to the labels parameter of legend().

main.py
import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [2, 4, 6, 8], label='Line A')
plt.plot([1, 2, 3, 4], [3, 6, 9, 12], label='Line B')

plt.legend(labels=['Line A', 'Line B'], loc='upper right')
plt.show()
211 chars
8 lines

This code will give a legend on the upper right corner of the plot containing the labels provided in labels list.

related categories

gistlibby LogSnag