remove frame around legend in python object-oriented plotting

  • Last Update :
  • Techknowledgy :

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)

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

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

Suggestion : 2

The simplest legend can be created with the plt.legend() command, which automatically creates a legend for any labeled plot elements:,By plotting empty lists, we create labeled plot objects which are picked up by the legend, and now our legend tells us some useful information. This strategy can be useful for creating more sophisticated visualizations.,As we have already seen, the legend includes all labeled elements by default. If this is not what is desired, we can fine-tune which elements and labels appear in the legend by using the objects returned by plot commands. The plt.plot() command is able to create multiple lines at once, and returns a list of created line instances. Passing any of these to plt.legend() will tell it which to identify, along with the labels we'd like to specify:,Plot legends give meaning to a visualization, assigning meaning to the various plot elements. We previously saw how to create a simple legend; here we'll take a look at customizing the placement and aesthetics of the legend in Matplotlib.

import matplotlib.pyplot as plt
plt.style.use('classic')
% matplotlib inline
import numpy as np
x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), '-b', label = 'Sine')
ax.plot(x, np.cos(x), '--r', label = 'Cosine')
ax.axis('equal')
leg = ax.legend();
ax.legend(loc = 'upper left', frameon = False)
fig
ax.legend(frameon = False, loc = 'lower center', ncol = 2)
fig
ax.legend(fancybox = True, framealpha = 1, shadow = True, borderpad = 1)
fig

Suggestion : 3

How to remove only the border of the box of the legend?,For the matplotlib object oriented approach:,How to change the color of the border of the legend box?,How to remove the box of the legend?

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)

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

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

Suggestion : 4

This guide makes use of some common terms, which are documented here for clarity:,A legend is made up of one or more legend entries. An entry is made up of exactly one key and one label.,This legend guide is an extension of the documentation available at legend() - please ensure you are familiar with contents of that documentation before proceeding with this guide.,Not all handles can be turned into legend entries automatically, so it is often necessary to create an artist which can. Legend handles don't have to exist on the Figure or Axes in order to be used.

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)
fig, ax = plt.subplots()
line_up, = ax.plot([1, 2, 3], label = 'Line 2')
line_down, = ax.plot([3, 2, 1], label = 'Line 1')
ax.legend(handles = [line_up, line_down])
fig, ax = plt.subplots()
line_up, = ax.plot([1, 2, 3], label = 'Line 2')
line_down, = ax.plot([3, 2, 1], label = 'Line 1')
ax.legend([line_up, line_down], ['Line Up', 'Line Down'])
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
red_patch = mpatches.Patch(color = 'red', label = 'The red data')
ax.legend(handles = [red_patch])

plt.show()
import matplotlib.lines as mlines

fig, ax = plt.subplots()
blue_line = mlines.Line2D([], [], color = 'blue', marker = '*',
   markersize = 15, label = 'Blue stars')
ax.legend(handles = [blue_line])

plt.show()
ax.legend(bbox_to_anchor = (1, 1),
   bbox_transform = fig.transFigure)

Suggestion : 5

Legends for curves in a figure can be added in two ways. One method is to use the legend method of the axis object and pass a list/tuple of legend texts for the previously defined curves:,The main idea with object-oriented programming is to have objects that one can apply functions and actions on, and no object or program states should be global (such as the MATLAB-like API). The real advantage of this approach becomes apparent when more than one figure is created, or when a figure contains more than one subplot.,With the grid method in the axis object, we can turn on and off grid lines. We can also customize the appearance of the grid lines using the same keyword arguments as the plot function:,One of the key features of matplotlib that I would like to emphasize, and that I think makes matplotlib highly suitable for generating figures for scientific publications is that all aspects of the figure can be controlled programmatically. This is important for reproducibility and convenient when one needs to regenerate the figure with updated data or change its appearance.

# This line configures matplotlib to show figures embedded in the notebook,
   # instead of opening a new window
for each figure.More about that later.
# If you are using an old version of IPython,
   try using '%pylab inline'
instead. %
   matplotlib inline
from pylab
import *
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 10)
y = x ** 2
figure()
plot(x, y, 'r')
xlabel('x')
ylabel('y')
title('title')
show()

Suggestion : 6

The example below explores a vector field using several traces. Note that you can click on legend items to hide or to select (with a double click) a specific trace. This will make the exploration of your data easier!,The fact that legend items are linked to traces means that when using discrete color, a figure must have one trace per color in order to get a meaningful legend. Plotly Express has robust support for discrete color to make this easy.,Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.,Traces corresponding to 2D fields (e.g. go.Heatmap, go.Histogram2d) or 3D fields (e.g. go.Isosurface, go.Volume, go.Cone) can also appear in the legend. They come with legend icons corresponding to each trace type, which are colored using the same colorscale as the trace.

import plotly.express as px

df = px.data.tips()
fig = px.scatter(df, x = "total_bill", y = "tip", color = "sex", symbol = "smoker", facet_col = "time",
   labels = {
      "sex": "Gender",
      "smoker": "Smokes"
   })
fig.show()
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x = "day", y = "total_bill", color = "smoker", barmode = "group", facet_col = "sex",
   category_orders = {
      "day": ["Thur", "Fri", "Sat", "Sun"],
      "smoker": ["Yes", "No"],
      "sex": ["Male", "Female"]
   })
fig.show()
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x = "day", y = "total_bill", color = "smoker", barmode = "stack", facet_col = "sex",
   category_orders = {
      "day": ["Thur", "Fri", "Sat", "Sun"],
      "smoker": ["Yes", "No"],
      "sex": ["Male", "Female"]
   })
fig.update_layout(legend_traceorder = "reversed")
fig.show()
import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Bar(name = "first", x = ["a", "b"], y = [1, 2]))
fig.add_trace(go.Bar(name = "second", x = ["a", "b"], y = [2, 1]))
fig.add_trace(go.Bar(name = "third", x = ["a", "b"], y = [1, 2]))
fig.add_trace(go.Bar(name = "fourth", x = ["a", "b"], y = [2, 1]))
fig.show()
import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Bar(name = "fourth", x = ["a", "b"], y = [2, 1], legendrank = 4))
fig.add_trace(go.Bar(name = "second", x = ["a", "b"], y = [2, 1], legendrank = 2))
fig.add_trace(go.Bar(name = "first", x = ["a", "b"], y = [1, 2], legendrank = 1))
fig.add_trace(go.Bar(name = "third", x = ["a", "b"], y = [1, 2], legendrank = 3))
fig.show()
import plotly.express as px

df = px.data.tips()
fig = px.histogram(df, x = "sex", y = "total_bill", color = "time",
   title = "Total Bill by Sex, Colored by Time")
fig.update_layout(showlegend = False)
fig.show()