1

From matplotlib library I have imported pyplot module. In that module there is an function plot() that I have used. Now my question is:

  1. Why the plot() function is not within any class? And if it s within any class why didn't we create any object of the class and used the plot() function.

  2. From the official documentation I learned that plot() returns a Line2D object. But the return of the plot() is not stored in any variable, yet we are using show() function. Generally it should be returned_object.show() but again the pyplot module has a show() function that is called without using any object just like plot() function. We are using just pyplot.show() to display the graph. How is it possible. I mean it makes more sense in either returned_object.show() or pyplot.show(the returned object from plot() function). How it shows that particular plot not the other random plot?

I have gone through the example code and plotted successfully. And in order to clear my doubts I have visited the official matplotlib module.


from matplotlib import pyplot as plt

years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]

gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]

# create a line chart, years on x-axis, gdp on y-axis
plt.plot(years, gdp, color='green', marker='o', linestyle='solid')

# add a title
plt.title("Nominal GDP")

# add a label to the y-axis
plt.ylabel("Billions of $")

plt.show()

Adam Cruge
  • 21
  • 3
  • A similar question has been asked [here](https://stackoverflow.com/questions/48398923/how-does-plt-show-know-what-to-show/48410495#48410495) and my answer to it shows a totally simplified mockup to make it transparent how pyplot works. – ImportanceOfBeingErnest Aug 18 '19 at 20:18

1 Answers1

1

The docs say that pyplot is a state-based interface to matplotlib.. It keeps the current state of your plot commands within itself -like the current Axes, Figure, Artists...

From the Tutorial:

In matplotlib.pyplot various states are preserved across function calls, so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes (please note that "axes" here and in most places in the documentation refers to the axes part of a figure and not the strict mathematical term for more than one axis).


The functions also return Artists, Lines, etc., so you can assign them to names and modify their properties to your hearts content.


It is worth reading through the Tutorials at least through the Legend Guide

wwii
  • 23,232
  • 7
  • 37
  • 77