How to make that subplots created in a for loop share the same scale and xticks (matplotlib)

Viewed 236

I have the following code snippet, to create 20 subplots, showing a line, with different markers. However, in y axis don't show the same scale, and they take part of some subplots, which makes the entire figure to look ugly.

import matplotlib.pyplot as plt
markers = [".", ",", "o","v","^","<",">","s","p","P","*","h","H","+","x","X","D","d", "|", "_"]
num_subplots = len(markers)
fig = plt.figure()
for i, j in zip(range(num_subplots), markers): 
    try: 
        i +=1
        data = np.random.random(10)
        ax = fig.add_subplot(5,5,i)
        ax.plot(data, marker = j)
    except Exception as e:
        print(e)

I found in this post some information regarding the sharex argument, which is useful, however I cannot implement this idea in a loop.

How to set same scale for subplots in python using matplotlib

1 Answers

Why don't you create the subplots first:

fig, axes = plt.subplots(4,5, sharex=True, sharey=True)
for marker, ax in zip(markers, axes.ravel()):
    try:
        data = np.random.random(10)
        ax.plot(data, marker=marker)
    except Exception as e:
        print(e)

Output:

enter image description here

Related