且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用子图将 seaborn 轴添加到 matplotlib 图?

更新时间:2023-11-21 16:00:58

You simply assign the axis on which you want to plot as input to the function and explicitly specify on which axis you want to plot in 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])