When plotting a plot using matplotlib:

  1. How to remove the box of the legend?
  2. How to change the color of the border of the legend box?
  3. How to remove only the border of the box of the legend?
3

Best Answer


When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()leg.get_frame().set_linewidth(0.0)

For the matplotlib object oriented approach:

axes.legend(frameon=False)leg = axes.legend()leg.get_frame().set_edgecolor('b')leg.get_frame().set_linewidth(0.0)

Removing the legend border in Matplotlib is a common task when creating plots. This can be achieved by modifying the legend properties using the legend() function and setting the frameon parameter to False. Here is an example:

import matplotlib.pyplot as plt# Create a plotplt.plot([1, 2, 3, 4], [1, 4, 9, 16], label='Data')# Remove the legend borderplt.legend(frameon=False)# Show the plotplt.show()

By default, the legend has a border around it. This border can be distracting in certain cases, and removing it can improve the appearance of the plot. However, keep in mind that removing the legend border may make it harder to distinguish the legend from the plot itself.

In conclusion, you can remove the legend border in Matplotlib by setting the frameon parameter of the legend() function to False. Experiment with different plot styles and settings to find the best option for your specific use case.

One more related question, since it took me forever to find the answer:

How to make the legend background blank (i.e. transparent, not white):

legend = plt.legend()legend.get_frame().set_facecolor('none')

Warning, you want 'none' (the string). None means the default color instead.