1. Learn
  2. /
  3. Courses
  4. /
  5. Analyzing Financial Statements in Python

Exercise

Updating the user-defined function for plotting

Recall the function to make plots from an earlier exercise:

def make_plot(dataset, ratio, comp_type):
  whole_dat = []
  for industry in comp_type:
    dat = dataset.loc[dataset["comp_type"]==industry]
    dat_avg = dat.pivot_table(index="Year",
                              values=ratio).reset_index()
    dat_avg["company"] = f"Avg {type}"
    dat_avg["comp_type"] = industry
    whole_dat.append(pd.concat([dat,
                                dat_avg]))

  plot_df = pd.concat(whole_dat).reset_index(drop=True)
  sns.relplot(data=plot_df,
              x="Year",
              y="gross_margin",
              hue="company",
              col="comp_type",
              kind="line")
  plt.show()
  plt.close()

Notice how this function can only make line plots with year on the x-axis. In this exercise, you will be introduced to an updated version of this function.

Instructions 1/3

undefined XP
    1
    2
    3

Question

The function has been updated like this:

def make_plot_updated(dataset, x, y, kind, comp_type):
  whole_dat = []
  for industry in comp_type:
    dat = dataset.loc[dataset["comp_type"]==industry]
    values = [x,y if y!="Year" else x]
    dat_avg = dat.pivot_table(index="Year",
                              values=values).reset_index()
    dat_avg = dat_avg.loc[:,
                          ~dat_avg.columns.duplicated()]
    dat_avg["company"] = f"Avg {type}"
    dat_avg["comp_type"] = industry
    whole_dat.append(pd.concat([dat, dat_avg]))

  plot_df = pd.concat(whole_dat).reset_index(drop=True)
  sns.relplot(data=plot_df,
              x=x,
              y=y,
              hue="company",
              col="comp_type",
              kind=kind)
  plt.show()
  plt.close()

In the code above, whole_dat is a list, and the command .append(x) essentially affixes x to the list it is applied to, which in this case is whole_dat.

Choose the correct option below. The function is loaded in the console for you to test it. The pandas DataFrame dataset is also available with operating margin and debt-to-equity ratio computed.

Possible answers