gpt4 book ai didi

python - 如何将 seaborn 轴添加到带有子图的 matplotlib 图?

转载 作者:行者123 更新时间:2023-12-05 03:01:45 32 4
gpt4 key购买 nike

我有一个返回 seaborn 图的函数。我想通过循环将多个 seaborn 图添加到一个图形中。我找到了答案 here适用于 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)

我想在 ax[0], ax[1], ax[2] 中看到 3 个图

最佳答案

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

关于python - 如何将 seaborn 轴添加到带有子图的 matplotlib 图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55593583/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com