pandas 如何为seaborn中的子图设置标题和ylims

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50232363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:32:39  来源:igfitidea点击:

How to set title and ylims for subplots in seaborn

pythonpython-3.xpandasmatplotlibseaborn

提问by Rocketq

I have such code which draws 2 subplots. I want set ylim and title for both subplots , but it applits only to the last subplot.

我有这样的代码,它绘制了 2 个子图。我想为两个 subplots 设置 ylim 和 title,但它仅适用于最后一个 subplot。

   TREATMENTINSTIDs = atg_cg.TREATMENTINSTID.unique()
    sn.set_style('ticks')
    fig, ax = plt.subplots(nrows = 2,ncols = 1)
    fig.set_size_inches(10, 12)
    i = 0
    #plt.title(TREATMENTINSTID)

    for TREATMENTINSTID in TREATMENTINSTIDs:
        plt.title(TREATMENTINSTID)
        plt.ylim(0, 1000)
        sn.violinplot(x="group_type", y="arpu" , hue = 'isSMS',ax=ax[i],cut=0, 
                      data=atg_cg[atg_cg.TREATMENTINSTID == TREATMENTINSTID],inner="quartile", split=True, title = TREATMENTINSTID)
        sn.despine(left=True)
        i = i + 1

enter image description here

在此处输入图片说明

What is wrong here? And why first subplot is floating or soaring above x axis?

这里有什么问题?为什么第一个子图在 x 轴上方浮动或飙升?

回答by DavidG

You probably want to set the title and the limits on the axes objects themselves using the object oriented API. This means you can control the title etc on an individual subplot which is easier than plt.titlewhen using multiple subplots:

您可能希望使用面向对象的 API 设置轴对象本身的标题和限制。这意味着您可以在单个子图上控制标题等,这比plt.title使用多个子图更容易:

You already have the axes objects when you create the figure fig, ax = plt.subplots(nrows = 2,ncols = 1). Therefore modify the setting of the title and ylim using set_titleand set_ylim.

创建图形时,您已经拥有轴对象fig, ax = plt.subplots(nrows = 2,ncols = 1)。因此,使用set_titleand修改标题和 ylim 的设置set_ylim

Your code becomes:

您的代码变为:

TREATMENTINSTIDs = atg_cg.TREATMENTINSTID.unique()
sn.set_style('ticks')
fig, ax = plt.subplots(nrows=2, ncols=1)
fig.set_size_inches(10, 12)
i = 0
# plt.title(TREATMENTINSTID)

for TREATMENTINSTID in TREATMENTINSTIDs:
    ax[i].set_title(TREATMENTINSTID)
    ax[i].set_ylim(0, 1000)
    sn.violinplot(x="group_type", y="arpu", hue='isSMS', ax=ax[i], cut=0,
                  data=atg_cg[atg_cg.TREATMENTINSTID == TREATMENTINSTID], inner="quartile", split=True,
                  title=TREATMENTINSTID)
    sn.despine(left=True)
    i = i + 1