1

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 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect. Thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.