Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn axes off for all subplots of a figure

I am creating a large array of subplots and I want to turn off axes for all the subplots. Currently I am achieving this by

fig, ax = plt.subplots(7, len(clusters))
fig.subplots_adjust(wspace=0, top=1.0, bottom=0.5, left=0, right=1.0)

for x in ax.ravel():
    x.axis("off")

but looping over the subplots to turn of the axes individually is ugly. Is there a way to tell subplots to turn od axes at creation time or some setting on Figure or pyplot that turns axes off globally. pyplot.axis('off') turns off axes just on the last subplot.

like image 424
Daniel Mahler Avatar asked Jan 08 '16 21:01

Daniel Mahler


1 Answers

I agree with @tcaswell that you should probably just use what you're already using. Another option to use it as a function is to use numpy.vectorize():

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(7, len(clusters))
np.vectorize(lambda ax:ax.axis('off'))(ax)

or, if you need to invoke it multiple times, by assigning the vectorized function to a variable:

axoff_fun = np.vectorize(lambda ax:ax.axis('off'))
# ... stuff here ...
fig, ax = plt.subplots(7, len(clusters))
axoff_fun(ax)

Again, note that this is the same thing that @tcaswell suggested, in a fancier setting (only slower, probably). And it's essentially the same thing you're using now.


However, if you insist on doing it some other way (i.e. you are a special kind of lazy), you can set matplotlib.rcParams once, and then every subsequent axes will automatically be off. There's probably an easier way to emulate axis('off'), but here's how I've succeeded:

import matplotlib as mpl

# before
mpl.pyplot.figure()
mpl.pyplot.plot([1,3,5],[4,6,5])

# kill axis in rcParams
mpl.rc('axes.spines',top=False,bottom=False,left=False,right=False);
mpl.rc('axes',facecolor=(1,1,1,0),edgecolor=(1,1,1,0));
mpl.rc(('xtick','ytick'),color=(1,1,1,0));

# after
mpl.pyplot.figure()
mpl.pyplot.plot([1,3,5],[4,6,5])

Result before/after:

before rcparamsafter rcparams

Hopefully there aren't any surprises which I forgot to override, but that would become clear quite quickly in an actual application anyway.

like image 126