Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

python - How does plt.show() know what to show?

My question is not about matplotlib in detail, but a general programming and question, and i'm looking for an answer on the mechanisms making this possible in python or matplotlib core.

Let's say I have a scatter plot using the code:

import matplotlib.pyplot as plt
plt.scatter(a,b)
plt.show()

I'm wondering how is this statement handled?
How does python (or matplotlib?) know what to plot and where to get the data?
How are these statement handled by interpreter?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Maybe I finally see the point of this question. Of course we cannot explain pyplot here, because that is much too complicated and would require a complete tutorial (which btw do exist). But we can have a look at how pyplot would work as a module in a very simplified manner.

So let's create myplot, the ultimative console plotting library. ;-)

The module myplot could look as follows. It has two functions, scatter and show and two variables, figures and plot. plot would store our coordinate system to plot to. figures would store the figures we create.

plot = """
^            
|            
|            
|            
|            
|            
+----------->"""

figures =  []

def scatter(X,Y):
    thisplot = list(plot[:])

    for x,y in zip(X,Y):
        thisplot[1+14*(6-y)+x] = "*"
    thisplot = "".join(thisplot)

    figures.append(thisplot)

def show():
    for fig in figures:
        print(fig)

Calling scatter creates a new figure from plot and stores it in the figures list. Calling show takes all figures from that list, and shows them (prints them in the console).

So using myplot would look exactly like the example above.

import myplot as mlt

mlt.scatter([2,3,4,5,6,8],[2,5,4,4,3,2])

mlt.show() 

Creating the output:

^            
|  *         
|   **       
|     *      
| *     *    
|            
+----------->

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...