1
votes

I have some troubles understanding how the matplotlib subplots allow for sharing axis between them. I saw some exemples but i could not modify one to fit my use case..; Here i replaced my data by uniforms so the plots wont be interesting but whatever...

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import cm

d = 4
n1 = 100000
n2 = 100

background_data = np.random.uniform(size=(n1,d))
foreground_data = np.random.uniform(size=(n2,d))

fig = plt.figure()

for i in np.arange(d):
    for j in np.arange(d):
        if i != j:
            ax = fig.add_subplot(d,d,1+i*d+j)
            ax = plt.hist2d(background_data[:, i], background_data[:, j],
                       bins=3*n2,
                       cmap=cm.get_cmap('Greys'),
                       norm=mpl.colors.LogNorm())
            ax = plt.plot(foreground_data[:,i],foreground_data[:,j],'o',markersize=0.2)

Q : How can i share the x and y axes for all plots ?

1

1 Answers

3
votes

By far the easiest option is to use sharex and sharey arguments of plt.subplots.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

d = 4
n1 = 100000
n2 = 100

background_data = np.random.uniform(size=(n1,d))
foreground_data = np.random.uniform(size=(n2,d))

fig, axs = plt.subplots(d,d, sharex=True, sharey=True)

for i in np.arange(d):
    for j in np.arange(d):
        if i != j:
            ax = axs[j,i]
            ax.hist2d(background_data[:, i], background_data[:, j],
                       bins=3*n2,
                       cmap=plt.get_cmap('Greys'),
                       norm=mpl.colors.LogNorm())
            ax.plot(foreground_data[:,i],foreground_data[:,j],'o',markersize=2)
        else:
            axs[j,i].remove()

fig.savefig("sharedaxes.png")            
plt.show()

Plot