[python] A note that started to understand the behavior of matplotlib.pyplot

Pyplot, a module for drawing graphs, is sometimes taken care of, but I was not accustomed to using it. I've finally been able to eliminate that haze recently, so I'll leave it as a note of my awareness.

Where I didn't understand personally

First is the basic graph output.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-np.pi, np.pi)
y = np.sin(x)

fig = plt.figure()
plt.plot(x, y)
plt.title("y = sin(x)")
plt.xlabel("x")
plt.ylabel("y")
fig.savefig("output.png ")

output.png

With this, the image is output as ʻoutput.png`, but personally, the behavior at this time did not fall into my mind. For example

--There is no evidence of creating a plt instance --I used the plt method to change the title of the graph, but I called the fig method to save it as an image. --The target when accessing with plt just by generating fig1, fig2, ... like fig changes in order as fig1, fig2, ...

(By the way, I didn't think that title () and xlabel () are class methods). Personally, I'm used to the flow of instance creation → method call, so I think I understood without hesitation if the method was as below.

#This does not work properly.
import matplotlib
import numpy as np

x = np.linspace(-np.pi, np.pi)
y = np.sin(x)

plt = matplotlib.pyplot() #I want you to create an instance here
plt.plot(x, y)
plt.title("y = sin(x)")
plt.xlabel("x")
plt.ylabel("y")
plt.figure.savefig("output.png ") #I want this to be a method of the plt instance

Why is it successful in the first way? And why doesn't it work the way I envisioned?

What's really going on

Find out who each of the elements in the first working script is (omip the numpy part).

The important thing is that ** plt is a module **, not a class. If plt was a class, I would like it to be instantiated somewhere, but because it was a module, it was already created when I imported it on the second line, so suddenlyfig = plt.figure ()andIt worked fine with plt.plot (x, y). Also, this is speculation, but if you think that the access destination is updated in plt when the fig instance is created, other questions may be convincing.

bonus

Now, in python, modules are created as singletons, so they refer to objects with the same id no matter where you call them. Therefore, if you call pyplot elsewhere, you will still be able to access the graph you have already created.

For example, suppose the following two files are in the same directory:

graph.py


import matplotlib.pyplot as plt
import numpy as np

def edit_graph():
    x = np.linspace(-np.pi, np.pi)
    y = np.sin(x)

    plt.plot(x, y)
    plt.title("y = sin(x)")
    plt.xlabel("x")
    plt.ylabel("y")

main.py


import matplotlib.pyplot as plt_main
import graph

graph.edit_graph()
plt_main.show()

If you execute python main.py in this state, the same sine wave graph as before will be output. In other words, it is possible to output a graph generated / edited in one script file in another script file without creating / passing an instance (although it is not recommended by design). You can also call the method savefig () in the matplotlib.figure.Figure class after executingfig = pyplot.figure ().

Summary

The main reason for this question was that I misunderstood plt as some kind of class or instance. I don't know why I thought so now ... It's not a big deal if you realize that plt is a module, but I think it will be better understood if you think about it again. ..

Finally, a summary of what I noticed this time.

--pyplot is a module and is usually used with a name like plt. --The pyplot module itself behaves like a class or its instance --Every time you execute fig = pyplot.figure (), a fig instance of the matplotlib.figure.Figure class is created, and each time you execute it, the access target by the pyplot module changes.

Recommended Posts

[python] A note that started to understand the behavior of matplotlib.pyplot
Python Note: The mystery of assigning a variable to a variable
A story that struggled to handle the Python package of PocketSphinx
[Python] A program that rotates the contents of the list to the left
A note about the python version of python virtualenv
[Python] A program that calculates the number of socks to be paired
[Python] Note: A self-made function that finds the area of the normal distribution
[Python] A program that counts the number of valleys
A memo to visually understand the axis of pandas.Panel
14 quizzes to understand the surprisingly confusing scope of Python
[Python] A program that compares the positions of kangaroos.
A note on the default behavior of collate_fn in PyTorch
Make the display of Python module exceptions easier to understand
[Note] Import of a file in the parent directory in Python
[Python3] List of sites that I referred to when I started Python
A Python script that compares the contents of two directories
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
A Python script that allows you to check the status of the server from your browser
[Python] A program to find the number of apples and oranges that can be harvested
The story that the version of python 3.7.7 was not adapted to Heroku
How to determine the existence of a selenium element in Python
How to check the memory size of a variable in Python
[Python] A memo that I tried to get started with asyncio
How to check the memory size of a dictionary in Python
A function that measures the processing time of a method in python
[Python3] Define a decorator to measure the execution time of a function
A script that returns 0, 1 attached to the first Python prime number
The story of making a module that skips mail with python
[Python] A simple function to find the center coordinates of a circle
Check the behavior of destructor in Python
[Python3] Understand the basics of Beautiful Soup
[Python] Understand the content of error messages
[python] [meta] Is the type of python a type?
The story of blackjack A processing (python)
A way to understand Python duck typing
Python Note: The secret role of commas
[Python] A program that rounds the score
[Python3] Understand the basics of file operations
Have Alexa run Python to give you a sense of the future
I'm stunned by the behavior of filter () due to different versions of Python
Python Note: When you want to know the attributes of an object
[Introduction to Python] How to sort the contents of a list efficiently with list sort
How to create a wrapper that preserves the signature of the function to wrap
A note about the functions of the Linux standard library that handles time
Python code to determine the monthly signal of a relative strength investment
I made a program to check the size of a file in Python
From a book that makes the programmer's way of thinking interesting (Python)
Python: I want to measure the processing time of a function neatly
I made a function to see the movement of a two-dimensional array (Python)
Note that I understand the algorithm of the machine learning naive Bayes classifier. And I wrote it in Python.
How to calculate the volatility of a brand
[Note] Export the html of the site with python.
Get the caller of a function in Python
Python Note: When assigning a value to a string
[Note] About the role of underscore "_" in Python
About the behavior of Model.get_or_create () of peewee in Python
Output in the form of a python array
A python amateur tries to summarize the list ②
A discussion of the strengths and weaknesses of Python
[Python] Throw a message to the slack channel
A layman wants to get started with Python