Python drawing Matplotlib

Source: Internet
Author: User
Tags cos dashed line sca sin

Go from Http:// chart drawing: Getting Started with the Matplotlib drawing library

Matplotlib is Python's most famous drawing library, which provides a complete set of command APIs similar to those of MATLAB, and is ideal for interactive line mapping. It can also be easily used as a drawing control, embedded in GUI applications.

Its documentation is quite complete, and there are hundreds of thumbnails on the gallery page, and the source program opens. So if you need to draw some kind of diagram, just browse/copy/paste it on this page and basically get it done.

Under Linux more famous data graph tool also has gnuplot, this is free, Python has a package can call gnuplot, but the syntax is not used, and the drawing quality is not high.

And matplotlib is stronger: Matlab syntax, Python language, latex paint quality (you can also use the built-in latex engine to draw the mathematical formula).

Matplotlib.pyplot Quick Draw

Quick Draw and theObject-oriented plotting

Matplotlib is actually a set of object-oriented drawing libraries in which each drawing element in the chart, such as line line2d, text text, scale, and so on, has an object in memory that corresponds to it.

To facilitate quick drawing Matplotlib The Pyplot module provides a set of drawing APIs similar to those of MATLAB, which hides the complex structure of many drawing objects inside this set of APIs. We only need to invoke the functions provided by the Pyplot module to achieve a quick drawing and to set the various details of the chart. The Pyplot module is simple to use, but it is not intended to be used in larger applications.

In order to wrap an object-oriented drawing library into a calling interface that only uses functions, the Pyplot module stores information such as the current chart and the current sub-graph. The current charts and sub-plots can be obtained using PLT.GCF () and PLT.GCA (), respectively, to "get current figures" and "Get current Axes". In the Pyplot module, many functions deal with the current figure or axes object, such as:

Plt.plot () actually gets the current axes object AX by PLT.GCA () and then calls the Ax.plot () method to implement a real drawing.

You can enter a similar "Plt.plot??" in Ipython. commands to see how the functions of the Pyplot module are packaged for various drawing objects.

Configuration Properties

Matplotlib each component of a chart that is drawn corresponds to an object, we can set their property values by calling the property setting method of these objects set_* () or the Pyplot module's property setting function Setp ().

Because Matplotlib is actually a set of object-oriented drawing libraries, you can also get the properties of an object directly

Configuration file

Drawing a picture requires configuring the properties of many objects, such as color, font, Linetype, and so on. We did not configure each of these properties at the time of drawing, and many were directly using the matplotlib default configuration.

Matplotlib These default configurations in a configuration file called "MATPLOTLIBRC", we can modify the default style of the chart by modifying the configuration file. The configuration file can be read in using Rc_params (), which returns a configuration dictionary, Rc_params () is called when the Matplotlib module is loaded, and the resulting configuration dictionary is saved to the Rcparams variable The matplotlib will be drawn using the configuration in the Rcparams dictionary, and the user can directly modify the configuration in this dictionary, and the changes will be reflected to the drawing elements created thereafter.

Draw a multi-sub-graph (quick Drawing)

The matplotlib of a common class in Figure -> Axes -> (Line2D, Text, etc.) a figure object can contain multiple sub-graphs (Axes), and in Matplotlib, a plot area is represented by a Axes object, which can be understood as a sub-graph.

You can use subplot () to quickly draw a chart with multiple sub-graphs, which are called in the following form:

Subplot (NumRows, Numcols, Plotnum)

Subplot divides the entire drawing area into numrows rows * Numcols column sub-regions and then numbers each sub-region in order from left to right, top to bottom, and the upper-left sub-area is numbered 1. If the three numbers of Numrows,numcols and Plotnum are less than 10, they can be abbreviated to an integer, such as subplot (323) and subplot (3,2,3) are the same. Subplot creates an Axis object in the area specified by Plotnum. If the newly created axis overlaps the previously created axis, the previous axis will be deleted.

Subplot () returns the Axes object it creates, and we can save it with a variable and then alternately make them the current axes object with SCA () and call plot () to draw in it.

Draw multiple charts (Quick Draw)

If you need to draw multiple charts at the same time, you can pass an integer argument to figure () to specify the ordinal of the graph object, and if the object specified by the sequence number already exists, the new object will not be created, but only let it be the current figure object.

Import NumPy as NP
Import Matplotlib.pyplot as Plt
Plt.figure (1) # Create a Chart 1
Plt.figure (2) # Create a Chart 2
Ax1 = Plt.subplot (211) # Create sub-figure 1 in chart 2
AX2 = Plt.subplot (212) # Create sub-figure 2 in chart 2
x = Np.linspace (0, 3, 100)
For I in Xrange (5):
    Plt.figure (1)  #? # Select Chart 1
    Plt.plot (x, Np.exp (I*X/3)) (AX1)   #? # Select the Figure 2 in Fig. 1
    Plt.plot (x, Np.sin (i*x)) (AX2)  # Select sub-figure 2 of chart 2
    Plt.plot (x, Np.cos (i*x)) ()

Show Chinese in chart

The font used in the default configuration file for Matplotlib does not display Chinese correctly. In order for the chart to display Chinese correctly, there are several solutions available.

    1. Specify the font directly in the program.
    2. Modify the configuration dictionary Rcparams at the beginning of the program.
    3. Modify the configuration file.

object-oriented drawing

The Matplotlib API contains three layers, and the artist layer handles all of the high-level structures, such as drawing and layout for working with charts, text, and curves. Usually we only deal with artist, without having to worry about the underlying drawing details.

The standard process for creating a chart directly using artists is as follows:

    • Create a Figure object
    • Create one or more axes or subplot objects with a figure object
    • A method that calls objects such as axies creates artists of various simple types
Import Matplotlib.pyplot as Plt
X1 = Range (0, 50)
Y1 = [num**2 for num in X1] # y = x^2
X2 = [0, 1]
Y2 = [0, 1]  # y = x
Fig = Plt.figure (figsize= (8,4))                      # Create A ' figure ' instance
Ax = Fig.add_subplot (111)               # Create A ' axes ' instance in the figure
Ax.plot (X1, Y1, X2, Y2)                 # Create A line2d instance in the axes ()
Fig.savefig ("Test.pdf")


Python Scientific Computing (numpy video ) matplotlib-Charting (quick Drawing) (object-oriented mapping) (for system learning)

What is matplotlib (mainly about object-oriented drawing, may be a bit messy for beginners)

Matplotlib.pylab Quick Draw

Matplotlib also provides a module called Pylab, which includes many of the functions commonly used in NumPy and Pyplot modules, making it easy for users to quickly calculate and draw, ideal for use in Ipython interactive environments. The Pylab module is loaded here using the following method:
>>> Import Pylab as pl

1 Installing NumPy and Matplotlib

>>> Import NumPy
>>> numpy.__version__

>>> Import Matplotlib
>>> matplotlib.__version__

22 Common chart types : line and scatter plots (using the plot () command), histogram (using the hist () command)

21 percent Line Chart & Scatter chart Line and scatter plots

2.1. Line plots 10 percent wire chart (a line that associates a set of x and Y values)

Import NumPy as NP
Import Pylab as Pl
x = [1, 2, 3, 4, 5]# make an array of x values
y = [1, 4, 9, 25]# make a array of y values for each x value
Pl.plot (x, y) # use Pylab to plot x and Y () # Show the plot on the screen

2.1.2 Scatter plot scatter plots

Change Pl.plot (x, y) to Pl.plot (x, y, ' o '), the blue version

2.2 Landscaping Making things look pretty

2.2.1 Lines color changing the line color

Red: Change Pl.plot (x, y, ' o ') to Pl.plot (x, Y, ' or ')

2.2.2 lines style changing the line style

Dashed line: Plot (x, Y, '--')

2.2.3 marker style Changing the marker style

Blue Star Type Markers:plot (x, y, ' b* ')

2.2.4 and axis titles and axis coordinate limits plot and axis titles and limits

Import NumPy as NP
Import Pylab as Pl
x = [1, 2, 3, 4, 5]# make an array of x values
y = [1, 4, 9, 25]# make a array of y values for each x value
Pl.plot (x, y) # use Pylab to plot x and Y
Pl.title (' Plot of y vs. X ') # give plot a title
Pl.xlabel (' x axis ') # Make axis labels
Pl.ylabel (' Y axis ')
Pl.xlim (0.0, 7.0) # Set Axis limits
Pl.ylim (0.0, 30.) () # Show the plot on the screen

2.2.5 plotting multiple graphs on a coordinate system plotting more than one plot on the same set of axes

The practice is straightforward, and in turn, it can be plotted:

Import NumPy as NP
Import Pylab as Pl
x1 = [1, 2, 3, 4, 5]# make x, y arrays for each graph
y1 = [1, 4, 9, 16, 25]
x2 = [1, 2, 4, 6, 8]
y2 = [2, 4, 8, 12, 16]
Pl.plot (x1, y1, ' R ') # use Pylab to plot x and Y
Pl.plot (x2, y2, ' G ')
Pl.title (' Plot of y vs. X ') # give plot a title
Pl.xlabel (' x axis ') # Make axis labels
Pl.ylabel (' Y axis ')
Pl.xlim (0.0, 9.0) # Set Axis limits
Pl.ylim (0.0, 30.) () # Show the plot on the screen

2.2.6 Legend Figure Legends

Pl.legend ((PLOT1, Plot2), (' Label1, Label2 '), ' best ', Numpoints=1)

The third parameter indicates where the legend is placed: ' Best ' upper ', ' upper left ', ' center ', ' lower left ', ' lower right '.

If you have specified a label when you plot in the current figure, such as Plt.plot (x,z,label= "$cos (x^2) $"), call Plt.legend () directly.

Import NumPy as NP
Import Pylab as Pl
x1 = [1, 2, 3, 4, 5]# make x, y arrays for each graph
y1 = [1, 4, 9, 16, 25]
x2 = [1, 2, 4, 6, 8]
y2 = [2, 4, 8, 12, 16]
PLOT1 = Pl.plot (x1, y1, ' R ') # use Pylab to plot x and y:give your plots names
Plot2 = Pl.plot (x2, y2, ' go ')
Pl.title (' Plot of y vs. X ') # give plot a title
Pl.xlabel (' x axis ') # Make axis labels
Pl.ylabel (' Y axis ')
Pl.xlim (0.0, 9.0) # Set Axis limits
Pl.ylim (0.0, 30.)
Pl.legend ([Plot1, Plot2], (' Red Line ', ' green circles '), "best", Numpoints=1) # make Legend () # Show the plot on the screen

2.3 Histogram histograms

Import NumPy as NP
Import Pylab as Pl
# make an array of the random numbers with a Gaussian distribution with
# mean = 5.0
# RMS = 3.0
# Number of points = 1000
Data = Np.random.normal (5.0, 3.0, 1000)
# Make a histogram of the data array
Pl.hist (data)
# Make plot labels
Pl.xlabel (' data ') ()

If you do not want the black outline can be changed to pl.hist (data, histtype= ' stepfilled ')

2.3.1 Custom Histogram bin width Setting the width of the histogram bins manually

Add these two lines

Bins = Np.arange ( -5., 1.) #浮点数版本的range
Pl.hist (data, bins, histtype= ' stepfilled ')

3 Draw multiple sub-graphs on the same artboard plotting more than one axis per canvas

If you need to draw multiple charts at the same time, you can give the figure an integer argument that specifies the ordinal of the icon, if the specified
If the drawing object of the ordinal already exists, the new object will not be created, but only let it be the current drawing object.

FIG1 = pl.figure (1)
Pl.subplot (211)
Subplot (211) divides the drawing area into 2 rows, including a total of two regions, and then creates an Axis object in area 1 (upper area). Pl.subplot (212) creates an Axis object in Region 2 (lower area).

You can play around with plotting a variety of layouts. For example, Fig. Created using the following commands:

F1 = pl.figure (1)
Pl.subplot (221)
Pl.subplot (222)
Pl.subplot (212)

When there are multiple axes in the drawing object, you can interactively adjust the spacing between the axes and the distance between the axes and the border by using the Configure Subplots button in the toolbar. If you want to adjust in the program, you can call the Subplots_adjust function, which has left, right, bottom, top, wspace, hspace and other key parameters, the values of these parameters are 0 to 1 decimal, They are the coordinates or lengths that are normalized after the width height of the drawing area is 1.

Pl.subplots_adjust (left=0.08, right=0.95, wspace=0.25, hspace=0.45)

4 drawing the data in the file plotting the contained in files

4.1 Reading from an ASCII file Reading data from ASCII files

There are a lot of ways to read files, and here's just a simple way to get more information from official documents and numpy to quickly process data (file access).

The Loadtxt method of NumPy can read the following text data directly to the NumPy two-dimensional array


# Fakedata.txt
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81


Import NumPy as NP
Import Pylab as Pl
# Use NumPy to load the data contained in the file
# ' Fakedata.txt ' into a 2-d array called data
data = Np.loadtxt (' fakedata.txt ')
# Plot the first column as X, and second column as Y
Pl.plot (data[:,0], data[:,1], ' ro ')
Pl.xlabel (' x ')
Pl.ylabel (' y ')
Pl.xlim (0.0, 10.) ()

4.2 Writing data to a file Writing a text file

There are a number of ways to write files, and here are just a few ways to write to a text file, and more information about the official documentation.

Import NumPy as NP
# Let's make 2 arrays (x, y) which we'll write to a file
# x is a array containing numbers 0 to ten, with intervals of 1
x = Np.arange (0.0, 10., 1.)
# y is a array containing the values in X, squared
y = x*x
print ' x = ', X
print ' y = ', y
# now open a file to write the data to
# ' W ' means open for ' writing '
File = open (' Testdata.txt ', ' W ')
# loop-over-line-want to-write to file
For I in range (len (x)):
    # Make a string for each line want to write
    # ' \ t ' means ' tab '
    # ' \ n ' means ' newline '
    # ' str () ' means you is converting the quantity in brackets to a string type
    txt = str (x[i]) + ' \ t ' + str (y[i]) + ' \ n '
    # write the txt to the file
    File.write (TXT)
# Close your file
File.close ()

This part is translated from: Python plotting Beginners Guide

Support for latex math formulas

Matlplotlib has some support for latex, and it's natural to remember to use the raw string syntax:

Xlabel (r "$\frac{x^2}{y^4}$")

In Matplotlib, you can use the Latex command to edit the formula, just precede the string with an "R"

Here are a simple example:

# Plain Text
Plt.title (' Alpha > Beta ')

Produces "Alpha > Beta".

Whereas this:

# Math Text
Plt.title (R ' $\alpha > \beta$ ')

Produces "".

Here is a simple example of what you can do.

Import Matplotlib.pyplot as Plt

x = Arange (1,1000,1)
r =-2
c = 5
y = [5* (a**r) for a in X]

Fig = Plt.figure ()

Ax = Fig.add_subplot (111)
Ax.loglog (X,y,label = r "$y = \frac{1}{2\sigma_1^2}, c=5,\sigma_1=-2$")
Ax.legend ()
Ax.set_xlabel (r "x")
Ax.set_ylabel (r "y")

Program execution results in 3, which is actually an example of Power-law, interested friends can continue Google.

Looking at a simple example of using Python for scientific computing, the following two lines of code draw in the current drawing object by calling the plot function:

Plt.plot (x,y,label= "$sin (x) $", color= "Red", linewidth=2)
Plt.plot (X,z, "b--", label= "$cos (x^2) $")

The plot function is very flexible to call, and the first sentence passes the X, y array to plot, specifying various properties with the keyword argument:

    • label : Give a name to the curve that is drawn, this name is displayed in the diagram (legend). As long as the "$" symbol is added before and after the string, Matplotlib uses the mathematical formula drawn by its built-in latex engine .
    • Color: Specify the colors of the curve
    • linewidth : Specify the width of the curve

for details, refer to the Matplotlib official tutorial:

Writing Mathematical expressions

    • Subscripts and superscripts
    • Fractions, binomials and stacked numbers
    • Radicals
    • Fonts
      • Custom fonts
    • Accents
    • Symbols
    • Example

Text Rendering with LaTeX

    • Usetex with Unicode
    • Postscript Options
    • Possible hangups
    • Troubleshooting

There are several questions:

    • Matplotlib.rcparams Property Dictionary
    • If you want it to work properly, you need to set text.markup = "Tex" in the MATPLOTLIBRC configuration file.
    • If you want all the text in the chart (including Axis tick marks) to be latex ' d, you need to set Text.usetex = True in MATPLOTLIBRC. If you use latex to write a paper, this is useful for keeping the chart and the rest of the paper consistent.
    • When using Chinese strings in matplotlib, remember to use Unicode format, for example: U ' Test Chinese display '

Matplotlib Usage Summary

Python drawing Matplotlib

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.