matplotlib Brief Tutorial

Introduction

Official Tutorial
Chinese Tutorial

Features

basic function

Introduction to use

  • Basic concepts
    Legend, marker; Figure, axes, Axis; Spines
    Artist (text, Line2D, Collection, Patch ...)
  • Data type
    array
  • Namespace
    matplotlib.pyplotwith numpyuse (pylab deprecated)
  • FIG generating a plurality of
    plt.subplots(row, col) may generate a plurality of axes
  • Interactive mode
    plt.draw()if you do not appear on the screen, call the function
  • Convenient features
    simplified segments:
    by path.simplifyand path.simplify_threshold
    simplifying the Marker:
    by markevery plt.plot(x, y, markevery=10)referring before Markevery Demo
    line block:
    mpl.rcParams['agg.path.chunksize'] = 0
    Use Rapid Format:
    In order to avoid other formats are changed, at the end of call can not change other settings
    import matplotlib.style as mplstyle
    mplstyle.use('fast')

    Pyplot example

  • Line charts, scatter plots, histograms
  • Color scattergram shown, FIG.
  • FIG plurality of drawing
  • Insert text
  • Insert mathematical formulas
  • Insert comment text
  • Axis will automatically adapt to different data: linear, exponential, etc.

The type of graph

  • line plot()
  • FIG plurality of sub subplot()
  • display image imshow()
  • Pseudo-color and contour pcolormesh(),contour()
  • Histogram hist()
  • path matplotlib.path
  • 3D 3D plotting
  • Flow chart streamplot()
  • Oval for certain specific tasks ..
  • Bar chart bar()
  • Pie pie()
  • form table()
  • Scatter scatter()
  • Filling curve fill()
  • Time series data matplotlib.tickerandmatplotlib.dates
  • Index semilogx(), semilogy()andloglog()
  • Polar plot polar()
  • Icon legend()
  • tex text matplotlib.mathtext;usetex

Picture example

  • Importing Pictures module import matplotlib.image as mpimg; can be used Pillow library, Matplotlibonly support PNG
  • Read picture img = mpimg.imread('../../doc/_static/stinkbug.png')
  • display image imgplot = plt.imshow(img)
  • Color bar plt.colorbar()
  • Different picture mode (set display range, etc.)

An example of a complete plot of

  • data
  • Download Data
  • 控制格式 plt.style.use('fivethirtyeight') plt.rcParams.update({'figure.autolayout': True})
    tips: Customizing Matplotlib with style sheets and rcParams
  • Plt change attributes, change more than once pyplot.setp()
  • FIG resizing fig, ax = plt.subplots(figsize=(8, 4))
  • Format Axis Control ax.xaxis.set_major_formatter(formatter) ticker.FuncFormatter
  • save Picture figure.Figure.savefig()

Using style sheets and a control format rcParams

style sheets
  • The optional format plt.style.available
  • Define your own format mpl_configdir/stylelib/presentation.mplstyle
  • Format Combination plt.style.use(['dark_background', 'presentation'])
  • Temporary format with plt.style.context('dark_background'):
rcParams
  • Directly matplotlib.rcParamsmodify the formatting, such asmpl.rcParams['lines.linewidth'] = 2
  • Using matplotlib.rc()modified form, such asmpl.rc('lines', linewidth=4, color='g')
  • Use matplotlib.rcdefaults()restore the default configuration
  • The default configuration in matplotlibrcfile

Intermediate function

Artist Tutorials

Three-tier structure:

  1. Drawing area matplotlib.backend_bases.FigureCanvas
  2. Drawing Methods matplotlib.backend_bases.Renderer
  3. Used rendererin canvasthe drawing on thematplotlib.artist.Artist

Artist divided into two categories:

  1. primitives include: Line2D, Rectangle, Text, AxesImage, etc
  2. containers include: Axis, AxesandFigure

Axes are usually distributed in rows and columns, use add_axes()in any position to create axes

legend Tutorial

legend entry: Each legend by one or more of legend entryconfiguration
legend key: left tag or color modes
legend label: text description of the handle
legend handle: The handle described

cycler Tutorial

Data processing cycle ps.

Figure layout change

subplots(): Create Layout and axes
GridSpec: Reset figure layout
SubplotSpec: a given layout, create a sub-graph
subplot2grid(): create a child within the grid of FIG.

Layout Tutorial

  • constrained_layout = ture Avoid the coordinates, text overlap
  • The impact colorbars, Suptitle, Legends layout
  • Manual layout
  • Another option tight_layout()

Pictures direction control

Through originthe extent kwargsaxes of the picture parameter control

Advanced Features

path

Draw a path path

Path effect

Set Path WordArt effect

Conversion coordinate system

Offset?

colour

Specify the color

Set the color method

  • RGB or RGBA float through 0-1 (0.1, 0.2, 0.5) or (0.1, 0.2, 0.5, 0.3)
  • RGB or RGBA strings #0f0f0for#0f0f0f80
  • 0-1 a floating point number gradation 0.5
  • Color abbreviation {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}
  • X11 / CSS4 color name black
  • xkcd color xkcd:sky blue
  • Uppercase C with digital C0according to style changes, with the highest number do not know how much ... (seaborn six colors axes.prop_cycle: cycler('color', ['4C72B0', '55A868', 'C44E52', '8172B2', 'CCB974', '64B5CD']))

Custom Colorbars

  • Substantially continuous colorbar
  • colorbar discrete intervals
  • Setting the length of the colorbar

Custom colormap

Get the value of the colormap changes; providing a plurality of colormap

colormap distribution

Generally linear profile, need to be adjusted in some cases

Select colormap

Select colormap color mode

text

Matplotlib Plots text

Basic Commands

  • The text axes anywhere to add text
  • Annotate anywhere on the annotate axes, an optional arrow
  • xlabel axes of the x-axis labels
  • ylabel axes y-axis labels
  • title axes title
  • On figtext figure anywhere to add text
  • suptitle figure add title

x- and y- axis-axis text format

  • Distribution location
  • Font format text parameters
  • Spacer pad

title

  • Distribution location
  • Spacer pad

Scale and the scale labels

  • Main scale, minor division
  • Range scale display
  • Scale display format

Attributes and text layout

  • alpha transparency
  • color color
  • position location
  • rotation rotation

Coordinate transformation?
Non-Latin characters?

Note

  • Text styles
  • Arrow format (which may be round, block, various arrows, etc.)
    PS. Highlight annotation data is realized by the marker

Mathematical expression

  • Support latex plot mathematical expressions
    ps. Use mathtype edit, export it

Use latex rendering text

no need..

actual use

According to the official document example + API documentation modify and use as needed

Use figure.Figure.savefig()Save as PDF

Guess you like

Origin www.cnblogs.com/DanielOwen/p/12158934.html