用户自定义函数绘图
在上一个练习中,您需要编写以下代码来绘图:
# Subset tech and fmcg companies
subset_dat = dataset.loc[dataset["comp_type"].isin(["tech", "fmcg"])]
# Compute yearly average gross margin ratio of tech and fmcg companies
subset_dat_avg = subset_dat.pivot_table(index=["Year", "comp_type"], values = "gross_margin").reset_index()
# Add column company
subset_dat_avg["company"] = np.where(subset_dat_avg["comp_type"]=="tech", "Avg tech", "Avg fmcg")
# Concat the DataFrames
plot_df = pd.concat([subset_dat, subset_dat_avg], axis=0)
# Make the plot
sns.relplot(data=plot_df.reset_index(drop=True), x="Year", y="gross_margin", hue="company", col="comp_type", kind="line")
plt.show()
plt.close()
请注意,在这个练习中,我们对 tech 和 FMCG 的 DataFrame 做了相同的处理。这很重复,违背了一个名为 DRY(Don't repeat yourself,不要重复自己)的编码原则。重复的代码会增加您的工作量,也更容易出错。在本练习中,您将定义自己的函数来处理数据并绘制图形。
本练习是课程的一部分
