Sometimes, the frame around a matplotlib plot can detract from the information you are trying to convey. How do you remove the frame, ticks, or axes from a matplotlib plot?
First, we construct a figure and an axes object:
fig1 = plt.figure(facecolor='white') ax1 = plt.axes(frameon=False)
The Axes object is a container that holds the axes, the ticks, the labels, the plot, the legend, etc. You will always have an Axes object, even if the axes are not visible! The keyword argument frameon=False turns the frame off. An alternative method is:
We’ll disable the drawing of ticks at the top of the plot:
Now, we’ll turn off the y axis:
Replace get_yaxis with get_xaxis to access the x axis. The problem is that now the x axis doesn’t have a line, so we’ll have to add one ourselves. Let’s assumed we’ve plotted some stuff. To add the x axis line:
xmin, xmax = ax1.get_xaxis().get_view_interval() ymin, ymax = ax1.get_yaxis().get_view_interval() ax1.add_artist(Line2D((xmin, xmax), (ymin, ymin), color='black', linewidth=2))
First, we obtain the limits of the current view. Then, we use these limits to define the length of the x axis line. This approach allows the line to dynamically adapt if the user changes the view limits in the plot window. Note that we have to use a linewidth of 2 to get a visible linewidth of 1, because the lower half of the lower half of the line is clipped. We use the add_artist method to add the line to the Axes object. This method is better than just plotting a line on the Axes, because we don’t want the axis to show up in the legend!
Get the full example on github.
An alternate approach is to use the AxesGrid Toolkit, which comes with versions of Matplotlib 0.99 or higher. Here is an example of how AxesGrid can display only the left and bottom axes.