9951 explained code solutions for 126 technologies

python-matplotlibHow to move legend outside of the chart

import matplotlib.pyplot as plt
plt.plot([1,2,10,6,15,3,4], label='A')
plt.plot([4,2,11,2,1,20,25], label='B')

h, l = plt.gca().get_legend_handles_labels()
plt.legend(loc=(0, 1.05),ncol=2)

plt.show()ctrl + c
import matplotlib.pyplot as plt

loads Matplotlib module to use plotting capabilities


plot specified data


set label for this line


returns legend labels and handlers


show and configure legend


configure legend location, we can pass coordinates tuple here

(0, 1.05)

place our legend in the top left corner a little higher than the chart top border


used to render legend labels horizontally


render chart in a separate window