python(41): Data visualization--Matplotlib introduction

Overview

Matplotlib is a Python graphics library that allows users to easily graph data and provides a variety of output formats.

Matplotlib can be used to draw various static, dynamic, and interactive charts.

Matplotlib is a very powerful Python drawing tool. We can use this tool to present a lot of data more intuitively in the form of charts.

Matplotlib can draw line graphs, scatter plots, contour plots, bar charts, histograms, 3D graphics, even graphic animations, and more.

The principle of using matplotlib for drawing is mainly to understand the relationship between figure (canvas), axes (coordinate system), and axis (coordinate axis). 

Introduction to graph objects

figure: canvas

A figure can contain any number of coordinate systems

axes: coordinate system

It is what is considered a "drawing". It is an image area with data space. An axes can only belong to one figure. An axes can contain two or three axes.

axis: coordinate axis

These are number line-like objects. They are responsible for setting the graph limits and generating ticks (markers on the axes) and tick labels (strings marking the ticks).

Matplotlib application

Matplotlib is usually used together with NumPy and SciPy (Scientific Python). This combination is widely used to replace MatLab. It is a powerful scientific computing environment that helps us learn data science or machine learning through Python.

SciPy is an open source Python algorithm library and mathematical toolkit.

SciPy includes modules for optimization, linear algebra, integration, interpolation, special functions, fast Fourier transform, signal processing and image processing, solving ordinary differential equations, and other calculations commonly used in science and engineering.

Pyplot is a sublibrary of Matplotlib and provides a drawing API similar to MATLAB.

Pyplot is a commonly used drawing module that allows users to draw 2D charts easily.

Pyplot contains a series of related functions for drawing functions. Each function will make some modifications to the current image, such as adding markers to the image, generating new images, generating new drawing areas in the image, etc.

NumPy (Numerical Python) is an extension library of the Python language that supports a large number of dimensional array and matrix operations. In addition, it also provides a large number of mathematical function libraries for array operations.

NumPy's predecessor, Numeric, was first developed by Jim Hugunin and other collaborators. In 2005, Travis Oliphant combined the features of another library of the same nature, Numarray, into Numeric, and added other extensions to develop NumPy. NumPy is open source and maintained and developed by many collaborators.

NumPy is a very fast mathematics library, mainly used for array calculations, including:

  • A powerful N-dimensional array object ndarray
  • Broadcast function
  • Tools for integrating C/C++/Fortran code
  • Linear algebra, Fourier transform, random number generation and other functions

Basic graphics 1:

import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([0, 6])
ypoints = np.array([0, 100])

plt.plot(xpoints, ypoints)
plt.show()

Graphic 2:

import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([6, 2, 13, 10])

plt.plot(ypoints, color = 'r')
plt.show()

Figure 3:

import matplotlib.pyplot as plt
import numpy as np

x = np.array(["Runoob-1", "Runoob-2", "Runoob-3", "C-RUNOOB"])
y = np.array([12, 22, 6, 18])

plt.bar(x, y,  color = ["#4CAF50","red","hotpink","#556B2F"])
plt.show()

Figure 4:

import math

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


def beta_pdf(x, a, b):
    return (x**(a-1) * (1-x)**(b-1) * math.gamma(a + b)
            / (math.gamma(a) * math.gamma(b)))


class UpdateDist:
    def __init__(self, ax, prob=0.5):
        self.success = 0
        self.prob = prob
        self.line, = ax.plot([], [], 'k-')
        self.x = np.linspace(0, 1, 200)
        self.ax = ax

        # Set up plot parameters
        self.ax.set_xlim(0, 1)
        self.ax.set_ylim(0, 10)
        self.ax.grid(True)

        # This vertical line represents the theoretical value, to
        # which the plotted distribution should converge.
        self.ax.axvline(prob, linestyle='--', color='black')

    def __call__(self, i):
        # This way the plot can continuously run and we just keep
        # watching new realizations of the process
        if i == 0:
            self.success = 0
            self.line.set_data([], [])
            return self.line,

        # Choose success based on exceed a threshold with a uniform pick
        if np.random.rand(1,) < self.prob:
            self.success += 1
        y = beta_pdf(self.x, self.success + 1, (i - self.success) + 1)
        self.line.set_data(self.x, y)
        return self.line,

# Fixing random state for reproducibility
np.random.seed(19680801)


fig, ax = plt.subplots()
ud = UpdateDist(ax, prob=0.7)
anim = FuncAnimation(fig, ud, frames=100, interval=100, blit=True)
plt.show()

 

 Official documentation:

Matplotlib: Python plotting — Download Matplotlib 3.3.3

Matplotlib Chinese

GitHub - matplotlib/matplotlib: matplotlib: plotting with Python

Guess you like

Origin blog.csdn.net/qq_37674086/article/details/125141916