简体   繁体   English

每行不同的 y 比例 Matplotlib

[英]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.我正在尝试为每一行子图动态缩放 y 轴,所以我想我会手动定义我将使用 for 循环创建的每个子图的 ymax。

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):我想要什么(注意每行不同的 y 轴):

在此处输入图片说明

Setting ylim manually won't work in your case sense sharey=True .手动设置ylim在您的情况下sharey=True If you set it to False, you can then set ylim for each plot (with separate y-ticks for each plot).如果将其设置为 False, ylim以为每个设置ylim (每个都有单独的 y-ticks)。

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.由于您似乎想要为每一共享一个 y ,因此您必须计算每一行的最大值并将其设置在内部循环之外。 Then, you can hide the ticks for all but the first plot in each row: ax.set_yticks([]) .然后,您可以隐藏每行中除第一个图以外的所有刻度: 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.我不知道这个功能在我写的原来的答复的时间存在,我只是没有意识到这一点,但今天这个实现的正确方法是使用: sharey='row'调用当subplots功能。 See here for more details.请参阅此处了解更多详情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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