简体   繁体   中英

Python matplotlib overwritten axes

I would like to plot data using multiple subplots on a grid that share the x and y axes while the their respective ticks don't appear every time. But I have some problem with the axes. Let me get into details:

#my data
dot_data1
dot_data2
all_data1
all_data2

#make a 2x4 grid
fig, ax = plt.subplots(nrows=2, ncols=4, sharex=True, sharey=True)

#for x axis
x0 = [0]
x  = list(range(1,10000))

#add subplots
for j in range(9):
    ax[j//4][j%4] = fig.add_subplot(2,4,j+1)
    ax[j//4][j%4].plot(x0, dot_data1[j], 'bo')
    ax[j//4][j%4].plot(x0, dot_data2[j], 'go')
    ax[j//4][j%4].plot(x , all_data1[j], 'b-')
    ax[j//4][j%4].plot(x , all_data2[j], 'g-')

#add the ticks
plt.setp(ax, xticks=[0,M], yticks=[i/10 for i in range(3, 11)])

Result

You can see that something is wrong. Ideally, I would like to have the xticks only 4 times and the yticks only twice. If not possible, I could go with 8 times as long as it's clear.

Bonus question: How to make the legends and/or the labels to only appear once?

the problem is your are adding new subplots over the ones you already had. Try this:

#make a 2x4 grid
fig, ax = plt.subplots(nrows=2, ncols=4, sharex=True, sharey=True)
axf=ax.flatten()
#for x axis
x0 = [0]
x  = list(range(1,10000))

#add subplots
for j,ax in enumerate(axf):
    ax.plot(x0, dot_data1[j], 'bo')
    ax.plot(x0, dot_data2[j], 'go')
    ax.plot(x , all_data1[j], 'b-')
    ax.plot(x , all_data2[j], 'g-')

#add the ticks
plt.show()

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