Home > Mobile >  How does this Matplotlib code snippet work
How does this Matplotlib code snippet work

Time:10-26

I am relatively new to programming with Pandas and Matplotlib.

I found this code snippet on this forum and used it successfully, but would like to understand it better.

fig, ax = plt.subplots(figsize=(20,20))
new_zinv2.plot(ax=ax, x_compat=True)

new_zinv2 is the name of my dataframe.

I would like to understand the contents inside the plot method, as this is the code snippet I lifted. What is the meaning of "ax=ax" and x_compat=True ?

I've tried to read the documentation, but I still don't understand (and I'd like to know how and why it works).

Thanks

CodePudding user response:

I'm going to rename the variables for clarity, but this changes nothing about the code.

The first lines:

import matplotlib.pyplot as plt
my_fig, my_ax = plt.subplots(figsize=(20, 20))

Use a function from matplotlib to create two objects, a figure, and a set of subplots. Since this function returns two things the assignment of my_fig, my_ax = assigns the first thing returned (the figure) to the variable my_fig and the second thing returned (the set of suplots) to the variable my_ax.

Then the second line:

new_zinv2.plot(ax=my_ax, x_compat=True)

uses the DataFrame function to plot. The plot function takes various arguments that you can use to change defaults or how you plot. ax=my_ax tells DataFrame.plot where to plot the figure, in this case it will plot the DataFrame on the (20,20) subplot we already created in the first line which we assigned to the variable my_ax, not it's own brand new default figure. x_compat=True is another argument you can specify and only takes a Boolean value, which in this case just modifies how the x-ticks are displayed for datetime values.

CodePudding user response:

So in the first command you give using the matplotlib library to generate a figure of size figsize and a pair of axes. The command plt.subplots() by documentation

Create a figure and a set of subplots

the default nrows, ncols is 1

fig, ax = plt.subplots(figsize=(20,20))

after that in the second line you are using the pandas library to plot your dataframe and you are specifying to do it on the ax axis you created before.

new_zinv2.plot(ax=ax, x_compat=True)

x_compat is just to suppress the tick resolution adjustment. Sometimes it gives you a cleaner display

  • Related