“This is the fifth day of my participation in the First Challenge 2022. For details: First Challenge 2022”

preface

I started learning machine learning again yesterday, so I’m going to prepare for the basics of machine learning today.

Matplotlib drawing library

Using this library we can draw a large number of pictures. And save, including the motion picture, but this should not be used often.

The drawing process

First we need panels for drawing, then we use panels for drawing, and finally show our pictures.


import matplotlib.pyplot as plt

plt.figure(figsize=(20.8),dpi=50)# Artboard, scale, pixel quality


plt.plot([1.2.3.4.5], [5.8.4.3.5], color='r', linestyle="--") #x,y, color, style

plt.show()# display, the image will be released after display, so please save the image before display

Copy the code

So the simple picture drawing here is almost done.

For drawing styles, see the following figure

beautify

We still need to beautify the picture. For example, add legend, add coordinates.

Add legend:

import matplotlib.pyplot as plt
import random
from pylab import mpl

Set to display Chinese font
mpl.rcParams["font.sans-serif"] = ["SimHei"]
# Set the normal display symbol
mpl.rcParams["axes.unicode_minus"] = False
# 0. Prepare data
x = range(60)
y_shanghai = [random.uniform(15.18) for i in x]
# 1. Create the canvas
plt.figure(figsize=(20.8), dpi=100)
# 2. Draw images
plt.plot(x, y_shanghai,label="Temperature")
# 2.1 Add x,y scale
# Construct x,y scale labels
x_ticks_label = ["At 11 {} minutes".format(i) for i in x]
y_ticks = range(40)
# scale display, can also display the label corresponding to the scale
plt.xticks(x[::5], x_ticks_label[::5])
plt.yticks(y_ticks[::5])
# 2.2 Add grid display
plt.grid(True, linestyle="--", alpha=0.5)
# 2.3 Adding a description
plt.xlabel("Time")
plt.ylabel("Temperature")
plt.title("Map of temperature change in a city from 11:00 to 12:00.", fontsize=20)
# 2.4 Image saving
plt.savefig("./test.png")
plt.legend(loc=0)
# 3. Image display
plt.show()
Copy the code

If you want to plot multiple polylines, you just need to plot again.

Draw the photos

We can also create a canvas that can be divided into multiple areas so that multiple images can be drawn in different Windows.

import matplotlib.pyplot as plt
import random
from pylab import mpl
# 0. Prepare data
x = range(60)
y_shanghai = [random.uniform(15.18) for i in x]
y_beijing = [random.uniform(1.5) for i in x]
# 1. Create the canvas
# plt.figure(figsize=(20, 8), dpi=100)
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20.8), dpi=100)
# 2. Draw images
# plt.plot(x, y_shanghai, label=" Shanghai ")
# PLT. The plot (x, y_beijing, color = "r", graphics.linestyle = "-", label = "Beijing")
axes[0].plot(x, y_shanghai, label="Shanghai")
axes[1].plot(x, y_beijing, color="r", linestyle="--", label="Beijing")
# 2.1 Add x,y scale
# Construct x,y scale labels
x_ticks_label = ["At 11 {} minutes".format(i) for i in x]
y_ticks = range(40)
# Scale display
# plt.xticks(x[::5], x_ticks_label[::5])
# plt.yticks(y_ticks[::5])
axes[0].set_xticks(x[::5])
axes[0].set_yticks(y_ticks[::5])
axes[0].set_xticklabels(x_ticks_label[::5])
axes[1].set_xticks(x[::5])
axes[1].set_yticks(y_ticks[::5])
axes[1].set_xticklabels(x_ticks_label[::5])
# 2.2 Add grid display
# PLT. The grid (True, graphics.linestyle = "-", alpha = 0.5)
axes[0].grid(True, linestyle="--", alpha=0.5)
axes[1].grid(True, linestyle="--", alpha=0.5)
# 2.3 Adding a description
# plt.xlabel(" time ")
# plt.ylabel(" temperature ")
# plt.title(" map of temperature change in a city from 11:00pm to 12:00pm ", fontsize=20)
axes[0].set_xlabel("Time")
axes[0].set_ylabel("Temperature")
axes[0].set_title("Map of temperature change in a city from 11:00 to 12:00.", fontsize=20)
axes[1].set_xlabel("Time")
axes[1].set_ylabel("Temperature")
axes[1].set_title("Map of temperature change in a city from 11:00 to 12:00.", fontsize=20)
# # 2.4 Image save
plt.savefig("./test.png")
# # 2.5 Add legend
# plt.legend(loc=0)
axes[0].legend(loc=0)
axes[1].legend(loc=0)
# 3. Image display
plt.show()
Copy the code

Draw different images

A scatter diagram


x = [225.98.247.07.253.14.457.85.241.58.301.01.20.67.288.64.163.56.120.06.207.83.342.75.147.9 , 53.06.224.72.29.51.21.61.483.21.245.25.399.25.343.35] y = [196.63.203.88.210.75.372.74.202.41.247.61.24.9 , 239.34.140.32.104.15.176.84.288.23.128.79.49.64.191.74.33.1 , 30.74.400.02.205.35.330.64.283.45] Figure (figsize=(20, 8), dpi=100) # 2 PLT. Scatter (x, y) # 3.

Copy the code

A histogram

movie_name = ['Thor: Ragnarok'.Justice League.'Murder on the Orient Express'.'Coco'.'Global Storm'.'Descent of demons'.'chase'.'Seventy-seven days'.'secret wars'.'rough beast'.'other']
Abscissa #
x = range(len(movie_name))
# box office data
y = [73853.57767.22354.15969.14839.8725.8716.8318.7916.6764.52222]
# 1. Create the canvas
plt.figure(figsize=(20.8), dpi=100)
# 2. Draw a bar chart
plt.bar(x, y, width=0.5, color=['b'.'r'.'g'.'y'.'c'.'m'.'y'.'k'.'c'.'g'.'b'])
# 2.1b Modify the scale display of the X-axis
plt.xticks(x, movie_name)
# 2.2 Add grid display
plt.grid(linestyle="--", alpha=0.5)
# 2.3 Add a caption
plt.title("Box office comparisons.")
# 3. Display images
plt.show()

Copy the code

animation

Plan a

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
y1 = []
x1 = []
for i in range(50):
    x1.append(i)
    y1.append(i)  # For each iteration, draw I in y1
    ax.cla()   # clear key
    ax.plot(x1,y1)

    plt.pause(0.1)

Copy the code

There’s another way to do it.

Scheme 2

We use the

from matplotlib.animation import FuncAnimation
Copy the code
  • FIG: canvas used to display dynamic effects, namely Figure object;
  • Func: function name, function function called repeatedly;
  • Frames: Each frame of data, usually an iterable, is taken out in turn and passed to a function function;
  • Init_func: initialization function, used to perform initialization operations;
  • Fargs: Extra arguments passed to function functions;
  • Save_count: save count. Default is 100.
  • Interval: Indicates the interval between repeated calls to function functions, expressed in milliseconds. The default value is 200.
  • Repeat_delay: The interval between executing the animation again after the animation ends, in milliseconds.
  • Repeat: whether the animation is repeated after execution, the default is True.
  • Blit: Whether to update all points, i.e. update all points or update only changed points. Default is False;
  • Cache_frame_data: whether to cache data. The default value is True.

For example, drawing a sinusoidal graph


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


fig = plt.figure(figsize=(10.5))  # to create figure
plt.rcParams["font.family"] = "FangSong"  # Support Chinese display
plt.ylim(-12.12)  # Y range
plt.yticks([-12 + 2 * i for i in range(13)], [...12 + 2 * i for i in range(13)])  Student: # y-scale
plt.xlim(0.2 * np.pi)  # X range
plt.xticks([0.5 * i for i in range(14)], [0.5 * i for i in range(14)])  # X scale
plt.title("Curve of function y = 10 * sin(x) at the interval [0,2 π")   # titles
plt.xlabel("X")  # X-axis tag
plt.ylabel("Y")  # Y tag
x, y = [], []  # to save drawing data, start with nothing, default null


def update(n) :  Update function
    x.append(n)  # add X coordinates
    y.append(10 * np.sin(n))  # add Y coordinates
    plt.plot(x, y, "r--")  # Draw a line chart


ani = FuncAnimation(fig, update, frames=np.arange(0.2 * np.pi, 0.1), interval=50, blit=False, repeat=False)  # Create an animation
plt.show()  # display images
Copy the code

Basically commonly used is these, not enough to check again.