简体   繁体   中英

Sharing axes for generated subplots matplotlib

OK, I've got myself thoroughly confused...
I have code that is generating a figure containing 8 sub-plots

import numpy as np
import matplotlib.pyplot as plt

names = ["one", "two", "three", "four", "five", "six", "seven", "eight"]
x = np.arange(1,11)
y = x**2.
z = x**1.5

fig = plt.figure()

fig.text(0.5, 0.02, "X axis", ha='center', fontsize=12)
fig.text(0.03, 0.5, "Y axis", va='center', rotation='vertical', fontsize=12)
palette = plt.get_cmap('tab10')

for name in names:
    i = names.index(name)+1 # What sub-plot are we on?
    graph = fig.add_subplot(4, 2, i)
# Add a new subplot to go in the grid (4x2)
    graph.set_title(f"plot {name}", fontsize=11)
    plot = graph.plot(x, y, color=palette(1))
    plot = graph.plot(x, z, color=palette(0))


plt.subplots_adjust(
top=0.93,
bottom=0.116,
left=0.124,
right=0.977,
hspace=0.972,
wspace=0.165)


plt.show()

It works fine, except I can't work out how to set the sub-plots so that they share x and y axes (I only want axes on the bottom edge for the x axis and left hand edge). All the examples I've been able to find seem to rely on each subplot having a different name that you can use to set sharex or sharey . Since I'm generating them as I go, there is nothing for the code to point to.

As per the comments, here is a working answer

fig, axs = plt.subplots(4, 2, sharex='all', sharey='all')
graphs = axs.flatten()

for ax in graphs:
    ax.plot(x,y,color=palette(0))
    ax.plot(x,z,color= palette(1))

I've changed from the fig.addplot version above to a version which sets up all the sub-plots beforehand ( plt.subplots(y,x) ), and then just uses the loop to populate them.

Still don't seem to be able to remove the tick marks on the hidden axes labels though...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM