matplotlib the usage guide learning

reference

Levels

Superlative: the matplotlib "state-machine environment". See the examples below, the use of the entire module plt function to do things, do not use the object's methods and properties.

import matplotlib.pyplot as plt

plt.figure(1)                # the first figure
plt.subplot(211)             # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212)             # the second subplot in the first figure
plt.plot([4, 5, 6])


plt.figure(2)                # a second figure
plt.plot([4, 5, 6])          # creates a subplot(111) by default

plt.figure(1)                # figure 1 current; subplot(212) still current
plt.subplot(211)             # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title

plt.show()

A secondary: a first layer of object-oriented interface. At this point, plt function module is only used to create a figure, axes and other objects, and then do things directly with the interface object.

x = np.arange(0, 10, 0.2)
y = np.sin(x)
fig, ax = plt.subplots()  
ax.plot(x, y)  # 使用ax的方法做事情
plt.show()

Objects

Alt

figure

Figure comprises a plurality of axes, it may not be a

  • Multiple figure, multiple axes
import matplotlib.pyplot as plt

plt.figure(1)                # the first figure
plt.subplot(211)             # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212)             # the second subplot in the first figure
plt.plot([4, 5, 6])


plt.figure(2)                # a second figure
plt.plot([4, 5, 6])          # creates a subplot(111) by default

plt.figure(1)                # figure 1 current; subplot(212) still current
plt.subplot(211)             # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title

plt.show()
  • A figure, no axes
fig = plt.figure()  # an empty figure with no axes
fig.suptitle('No axes on this figure')  # Add a title so we know which it is
# plt.plot([1,2,3])  # draw a line (now have an axes)
# plt.show()  # show the plot

axes

A target member has a plurality of axes objects axis (2D plot there are two, are x and y axes; 3D plot has three)

import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.2)
y = np.sin(x)
fig, ax = plt.subplots()
fig.suptitle("basic math")
ax.plot(x, y, label='sin')  # 使用ax的方法做事情
ax.set_title('sin function')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_xlim(-1, 11)
ax.legend()
plt.show()

data

Preferably np.array data, pd, and may be np.matrix following conversion

a = pandas.DataFrame(np.random.rand(4,5), columns = list('abcde'))
a_asarray = a.values

b = np.matrix([[1,2],[3,4]])
b_asarray = np.asarray(b)

mpl, plt and pylab

matplotlib is a package, pyplot is a module under matplotlib, pylab collection pyplot and numpy form a unified namespace (is deprecated).

For plt, the function of which there is always a current figure and the current axes (created automatically)

x = np.linspace(0, 2, 100)

plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')

plt.xlabel('x label')
plt.ylabel('y label')

plt.title("Simple Plot")

plt.legend()

plt.show()

Code style

  • Np explicitly import plt and reuse, not all of the objects introduced therein, to avoid contamination namespace
  • Use plt create axes and figure objects, and then use a control method further object
  • Np make use of data
  • Use plt display image
# 导入方式
import matplotlib.pyplot as plt
import numpy as np

def my_plotter(ax, data1, data2, param_dict):
    """
    A helper function to make a graph

    Parameters
    ----------
    ax : Axes
        The axes to draw to

    data1 : array
       The x data

    data2 : array
       The y data

    param_dict : dict
       Dictionary of kwargs to pass to ax.plot

    Returns
    -------
    out : list
        list of artists added
    """
    out = ax.plot(data1, data2, **param_dict) # 使用对象操作
    return out 

# which you would then use as:

data1, data2, data3, data4 = np.random.randn(4, 100) # 数据
fig, (ax1, ax2) = plt.subplots(1, 2) # 获取figure和axes对象
my_plotter(ax1, data1, data2, {'marker': 'x'})
my_plotter(ax2, data3, data4, {'marker': 'o'})
plt.show()

rear end

Interactive and non-interactive back-end back-end

Specify the backend

  1. backend parameters matplotlibrc file (my computer, this file is located in
    C: \ Users \ xxxx \ PycharmProjects \ untitled1 \ venv \ Lib \ site-packages \ matplotlib \ under mpl-data)
    Here Insert Picture Description
  2. Specified in the screenplay
import matplotlib
matplotlib.use('PS')   # generate postscript output by default

At this point if there is plt.show script () does not display pictures, and will be reported UserWarning:
Here Insert Picture Description

  1. Environment variable (that no specific examples)

Performance considerations

The main simplification is the render, comprising a line, mark, etc., can be used as simple fast mode setting

import matplotlib.style as mplstyle
mplstyle.use('fast')
Published 135 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/math_computer/article/details/103646840