在Seaborn多重绘图中调整y轴

时间:2019-07-18 19:21:54

标签: python matplotlib seaborn

我正在从仿真结果中绘制CSV文件。该图在同一图fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(24, 6))中具有三个图形。

但是,出于比较的目的,我希望所有图中的y轴从零开始,以特定值结束。我尝试了Seaborn作者提到的here解决方案。我没有收到任何错误,但是该解决方案也不适用于我。

这是我的剧本:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

fname = 'results/filename.csv'

def plot_file():
    fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(24, 6))
    df = pd.read_csv(fname, sep='\t')
    profits = \
        df.groupby(['providerId', 'periods'], as_index=False)['profits'].sum()

    # y-axis needs to start at zero and end at 10
    g = sns.lineplot(x='periods',
                     y='profits',
                     data=profits,
                     hue='providerId',
                     legend='full',
                     ax=axes[0])

    # y-axis need to start at zero and end at one
    g = sns.scatterplot(x='periods',
                        y='price',
                        hue='providerId',
                        style='providerId',
                        data=df,
                        legend=False,
                        ax=axes[1])
    # y-axis need to start at zero and end at one
    g = sns.scatterplot(x='periods',
                        y='quality',
                        hue='providerId',
                        style='providerId',
                        data=df,
                        legend=False,
                        ax=axes[2])

    g.set(ylim=(0, None))
    plt.show()

    print(g) # -> AxesSubplot(0.672059,0.11;0.227941x0.77)

结果图如下:

enter image description here

如何调整每个单独的图?

1 个答案:

答案 0 :(得分:0)

根据编写代码的方式,您可以使用g.axis引用每个子图轴并使用g.axis.set_ylim(low,high)。 (与链接的答案相比,不同之处在于您的图形未绘制在深奥的FacetGrid上。)

使用虚拟数据和不同轴范围的示例进行说明:

df = pd.DataFrame(np.random.uniform(0,10,(100,2)), columns=['a','b'])

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(8,4))


g = sns.lineplot(x='a',
                 y='b',
                 data=df.sample(10),
                 ax=axes[0])
g.axes.set_ylim(0,25)

g = sns.scatterplot(x='a',
                    y='b',
                    data=df.sample(10),
                    ax=axes[1])
g.axes.set_ylim(0,3.5)

g = sns.scatterplot(x='a',
                    y='b',
                    data=df.sample(10),
                    ax=axes[2])
g.axes.set_ylim(0,0.3)

plt.tight_layout()
plt.show()

enter image description here