创建一个函数作为pandas列(变量)的输入之一来创建绘图



我有一个包含多个列和变量的数据帧。我想创建一个函数来应用于数据帧的一些变量,以创建一些表示均值、中值和模式的显示。我找到了一个很好的代码来做到这一点,您稍后会看到。

我的问题是,我想自动创建显示,而不是每次我想在另一个变量上创建绘图时都复制粘贴它,我不知道如何做到这一点。

这是代码(我想很容易地更改变量"fat_100g"(:

f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {"height_ratios": (0.2, 1)})
mean=df['fat_100g'].mean()
median=df['fat_100g'].median()
mode=df['fat_100g'].mode().to_numpy()[0]
sns.boxplot(df["fat_100g"], ax=ax_box)
ax_box.axvline(mean, color='r', linestyle='--')
ax_box.axvline(median, color='g', linestyle='-')
ax_box.axvline(mode, color='b', linestyle='-')
sns.distplot(df["fat_100g"], ax=ax_hist)
ax_hist.axvline(mean, color='r', linestyle='--')
ax_hist.axvline(median, color='g', linestyle='-')
ax_hist.axvline(mode, color='b', linestyle='-')
plt.legend({'Mean':mean,'Median':median,'Mode':mode})
ax_box.set(xlabel='')
plt.show()

您可以创建一个变量,将其称为key=(无论您想要什么(,然后使用:

mean=df[key].mean()

如果你想循环浏览所有这些:

for key in list(df.columns):
##Do the plotting code; pay attention to not overwriting axes if you want to do this, maybe make ax a list and loop through the list using ax[ind] and add to the ind every loop?

最新更新