The first step in Python Matplotlib

Matplotlib --Graph drawing library -Official site --Use in combination with basic Python + Numpy + matplotlib + SciPy + etc.

Installation

pip install matplotlib

First example

import matplotlib.pyplot as plt #curse

squares = [1, 4, 9, 16, 25]
plt.plot(squares) #In default, points are connected by a straight line
plt.show() #Follow the instructions above to draw and show

image.png

Japanese display

The default is that Japanese cannot be used, so a little setting is required. In short, change the font setting of ** matplotlib ** to the font that supports Japanese.

  1. Download IPAex font from https://ipafont.ipa.go.jp/node17#jp, "IPAex font Ver.004.01" is the latest at the moment
  2. Unzip the downloaded file and copy the ʻipaexg.ttf` file inside to $ {object path} \ venv \ Lib \ site-packages \ matplotlib \ mpl-data \ fonts \ ttf
  3. $ {object path} \ venv \ Lib \ site-packages \ matplotlib \ mpl-data opens ** matplotlibrc ** below
  4. Search by ** font.family **
  5. Add font.family: IPAexGothic under # font.family: sans-serif
  6. Delete all the contents of the ** matplotlib ** cache destination

You can find out the font path and cache location with the code below

print(matplotlib.matplotlib_fname())   #Font path
print(matplotlib.get_cachedir())       #Where to save the cache

The other way is not to modify the config file, but you have to add the following code every time

plt.rcParams['font.sans-serif']=['IPAexGothic']

Or

plt.rcParams["font.family"] = "IPAexGothic"

decoration

import matplotlib.pyplot as plt

squares = [1, 4, 9, 16, 25]
plt.plot(squares, linewidth = 5)  #Make the line a little thicker

plt.title("square", fontsize = 24)
plt.xlabel("value", fontsize = 14)
plt.ylabel("The square of the value", fontsize = 14)

#Axis scale display settings
plt.tick_params(axis = 'both', labelsize = 14)
plt.show()

image.png

import numpy as np
import matplotlib.pyplot as plt

#0 to 5 to 0.Lines look smooth by creating 2-step dots
x = np.arange(0., 5., 0.2)
plt.plot(x, x * x)

plt.title("square", fontsize = 24)
plt.xlabel("value", fontsize = 14)
plt.ylabel("The square of the value", fontsize = 14)

#Set the font size of the scale to a slightly larger size
plt.tick_params(labelsize = 30)

plt.show()

image.png

If you increase the size of the scale, the X-axis and Y-axis labels will stick out and you will not be able to see them. Of course, you can adjust the screen size to make them visible, but you can change plt.tight_layout () to plt. If you put it before show () , it will be displayed automatically.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0., 5., 0.2)
plt.plot(x, x * x)

plt.title("square", fontsize = 24)
plt.xlabel("value", fontsize = 14)
plt.ylabel("The square of the value", fontsize = 14)

plt.tick_params(labelsize = 30)

plt.tight_layout()
plt.show()

image.png

I want to display as dots (scatter plot)

Use scatter ().

import matplotlib.pyplot as plt

x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16, 25]
plt.scatter(x_values, y_values, s=100)  #s specifies the size of the point

plt.show()

image.png

Data is obtained from automatic calculation

import matplotlib.pyplot as plt

x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
plt.scatter(x_values, y_values, s=4)

plt.axis([0, 1100, 0, 1100000])  #Axis range
plt.show()

image.png

Color customization

You can specify the color with the parameter c

plt.scatter(x_values, y_values, c='red', s=40)

It can also be specified in RGB. It is also possible to specify each RGB color element with a tuple of 0.0 to 1.0.

plt.scatter(x_values, y_values, c=(0, 0, 0.8), s=40)

Color map

A color map represents the correspondence between values and colors used when drawing. When visualizing data, the selection of color maps can emphasize the rules of data change. For example, a light color represents a small value, and a dark color emphasizes a large value.

import matplotlib.pyplot as plt

x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues)

plt.show()

image.png

For details, refer to Official Site. Examples ⇒ Color

Save graph

Use plt.savefig () instead ofplt.show ()

plt.savefig(`squares_plot.png`, bbox_inches='tight')

If you specify bbox_inches ='tight', extra whitespace will be cut off. The extension of the file that can be saved is

eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff

Hide axis

plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)

Size adjustment

plt.figure(figsize=(10, 6))   #The unit is inches
plt.figure(dpi=128, figsize=(10, 6))   #The default is 80dpi

Recommended Posts

The first step in Python Matplotlib
The first step in the constraint satisfaction problem in Python
MongoDB for the first time in Python
Python--The first step in Pygal
Download the file in Python
Find the difference in Python
The first step to getting Blender available from Python
First simple regression analysis in Python
First Python 3 ~ The beginning of repetition ~
Python in the browser: Brython's recommendation
Save the binary file in Python
Hit the Sesami API in Python
Get the desktop path in Python
Get the script path in Python
In the python command python points to python3.8
Implement the Singleton pattern in Python
[GUI with Python] PyQt5-The first step-
Hit the web API in Python
Heatmap with Dendrogram in Python + matplotlib
C / C ++ programmer challenges Python (first step)
See python for the first time
I wrote the queue in Python
Examine the object's class in python
Get the desktop path in Python
[Python] The first step to making a game with Pyxel
Get the host name in Python
Access the Twitter API in Python
I wrote the stack in Python
Master the weakref module in Python
The first step in speeding up inference with TensorFlow 2.X & TensorRT
Can Python implement the Dependency Inversion Principle (DIP) in the first place?
Play by hitting the Riot Games API in Python First half
Generate a first class collection in Python
Display LaTeX notation formulas in Python, matplotlib
Learn the design pattern "Prototype" in Python
Learn the design pattern "Builder" in Python
Try using the Wunderlist API in Python
[Python] Set the graph range with matplotlib
Displaying candlestick charts in Python (matplotlib edition)
Specify the color in the matplotlib 2D map
Check the behavior of destructor in Python
Continuously play the first Python Sukusta MV
Learn the design pattern "Flyweight" in Python
Try using the Kraken API in Python
Debug step execution in Python (Bottle, Intellij)
Learn the design pattern "Observer" in Python
Learn the design pattern "Memento" in Python
Learn the design pattern "Proxy" in Python
Write the test in a python docstring
Learn the design pattern "Command" in Python
OR the List in Python (zip function)
Display Python 3 in the browser with MAMP
Tweet using the Twitter API in Python
Learn the design pattern "Bridge" in Python
Check if the URL exists in Python
Learn the design pattern "Mediator" in Python
Associate the table set in python models.py
The result of installing python in Anaconda
What is "mahjong" in the Python library? ??
Read the file line by line in Python
Read the file line by line in Python