如何将seaborn轴添加到带有子图的matplotlib图形中?

2024-03-17

我有一个返回seaborn 情节的函数。我想通过循环将多个seaborn图添加到一个图形中。我找到了答案here https://stackoverflow.com/questions/6309472/matplotlib-can-i-create-axessubplot-objects-then-add-them-to-a-figure-instance对于 matplotlib 但不知道如何将其应用于 seaborn。

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 个地块ax[0], ax[1], ax[2]


您只需将要绘制的轴指定为函数的输入,并在 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])

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将seaborn轴添加到带有子图的matplotlib图形中? 的相关文章

随机推荐