如何使用子图将海底轴添加到matplotlib图中?

时间:2019-04-09 13:03:00

标签: python matplotlib seaborn

我有一个功能可以返回海图。我想通过循环将多个seaborn图添加到一个图。我找到了matplotlib的答案here,但不确定如何将其应用于seaborn。

ConversionService

我想在import pandas as pd import numpy as np import seaborn as sns from matplotlib import pyplot as plt def plotf(df_x): g = sns.lineplot(data=df_x[['2016','2017','2018']]) g.set_xticks(range(0,12)) g.set_xticklabels(['Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan']) return g df = pd.DataFrame({'Period': list(range(1,13)), '2016': np.random.randint(low=1, high=100, size=12), '2017': np.random.randint(low=1, high=100, size=12), '2018': np.random.randint(low=1, high=100, size=12)}) fig, ax = plt.subplots(nrows=3) 中看到3个地块

1 个答案:

答案 0 :(得分:1)

您只需将要在其上绘制的轴分配给函数,并在sns.lineplot中明确指定要在哪个轴上绘制

import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt

def plotf(df_x,ax):
    g = sns.lineplot(data=df_x[['2016','2017','2018']],ax=ax)
    g.set_xticks(range(0,12))
    g.set_xticklabels(['Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan'])
    return g

df = pd.DataFrame({'Period': list(range(1,13)),
                           '2016': np.random.randint(low=1, high=100, size=12),
                           '2017': np.random.randint(low=1, high=100, size=12),
                           '2018': np.random.randint(low=1, high=100, size=12)}) 

fig, ax = plt.subplots(nrows=3)
plotf(df,ax[0])
plotf(df,ax[1])
plotf(df,ax[2])

output