简体   繁体   中英

Different y scale for each row Matplotlib

I'm trying to dynamically scale the y-axes for each row of subplots, so i figured I would manually define the ymax for each subplot I would create with the for loop.

fig, ax = plt.subplots(3, len(motif.strip()), figsize=(15, 10), sharex=True, sharey=True)

    for i, s in enumerate(dataw.pos.unique()):
        for j, r in enumerate(dataw.type.sort_values().unique()):
            atmp = dataw[(dataw.pos == s) & (dataw.type == r)]
            btmp = dataw[(dataw.type == r)]
            ymax = (btmp['values'].values).max()
            #print(btmp)
            #print(ymax)
            tmp = [atmp[atmp['base'] == 'A']['values'].values,
                   atmp[atmp['base'] == 'G']['values'].values,
                   atmp[atmp['base'] == 'T']['values'].values,
                   atmp[atmp['base'] == 'C']['values'].values]

            ax[j][i].violinplot(tmp)
            ax[j][i].set_ylim([0, ymax])

            #ax[j][i].set(xlabel='base',
            #             ylabel='values',
            #             title=s + '--' + r)

    fig.tight_layout()

    fig.savefig(str(graph) + ".png")

What I have right now:

在此处输入图片说明

What I would like to have (note different y axes for each row):

在此处输入图片说明

Setting ylim manually won't work in your case sense sharey=True . If you set it to False, you can then set ylim for each plot (with separate y-ticks for each plot).

Since it seems you want a shared y for each row , you will have to calculate the max value for each row and set it outside of the internal loop. Then, you can hide the ticks for all but the first plot in each row: ax.set_yticks([]) .

Update

I don't know if this feature existed at the time I wrote the original answer and I was just not aware of it, but the correct way of achieving this today is to use: sharey='row' when calling the subplots function. See here for more details.

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