Python Chart drawing: Getting Started with the Matplotlib drawing gallery __python

Source: Internet
Author: User
Tags cos dashed line sca
Python 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 MATLAB, and is ideal for interactive line drawing. It can also be conveniently embedded in GUI applications as a drawing control.

Its documentation is fairly complete, and there are hundreds of thumbnails on the Gallery page, which are available after they are opened. So if you need to draw some kind of diagram, just browse/copy/paste it in this page, and basically you can do it.

Under Linux more famous data map tools and gnuplot, this is free, Python has a package can call gnuplot, but syntax is not accustomed to, and paint quality is not high.

And Matplotlib is stronger: The syntax of MATLAB, Python language, latex paint quality (can also use the built-in Latex engine to draw the mathematical formula).

Matplotlib.pyplot Quick Drawing

Quick Drawing and object-oriented way of drawing

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

In order 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 function provided by the Pyplot module to implement the quick drawing and to set the various details of the chart. The Pyplot module is not suitable for use in larger applications, although its usage is simple.

In order to wrap an object-oriented drawing library into a function-only calling interface, the Pyplot module internally holds information such as the current diagram and the current child graph. The current chart and child graphs can be obtained using PLT.GCF () and PLT.GCA (), respectively, "get-current Figure" and "Getting current Axes". In the Pyplot module, many functions are processed for the current figure or axes object, such as:

Plt.plot () actually obtains the current axes object ax through PLT.GCA (), and then calls the Ax.plot () method to implement the real drawing.

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

Configuration Properties

Matplotlib each part of the chart that is plotted corresponds to an object, we can set their property values by calling the object's property setting method 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 properties of objects directly

configuration file

Drawing a picture requires that you configure the properties of many objects, such as color, font, line style, and so on. When we are drawing, we do not configure these attributes individually, many of which are 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. A configuration file can be read in using Rc_params (), which returns a configuration dictionary, calls Rc_params () when the Matplotlib module is loaded, and saves the resulting configuration dictionary to the Rcparams variable ; Matplotlib will draw using the configuration in the Rcparams dictionary, and the user can modify the configuration in this dictionary directly, and the changes will be reflected in the drawing elements that are created thereafter.

Draw multiple child graphs (quick Drawing)

The matplotlib of common classes in the Figure-> Axes-> (line2d, Text, etc.) A figure object can contain multiple child graphs (Axes), and a Axes object represents a plot area in Matplotlib, which can be understood as a child graph.

You can use subplot () to quickly draw a chart that contains multiple child graphs, which are called as follows:

Subplot (NumRows, Numcols, Plotnum)

Subplot divides the entire drawing area into numrows row * numcols columns, and then numbers each of the subregions in order from left to right, from top to bottom, with the number of the child region on the left 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 with the previously created axis, the previous axis will be deleted.

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

Draw Multiple Charts (quick Drawing)

If you need to draw multiple charts at the same time, you can pass an integer argument to figure () to specify the ordinal number of the figure object, and if the figure object specified by the ordinal already exists, it will not create a new object, but simply make it the current figure object.

Import NumPy as NP
Import Matplotlib.pyplot as Plt
Plt.figure (1) # Create Chart 1
Plt.figure (2) # Create Chart 2
Ax1 = Plt.subplot (211) # Create a child Figure 1 in chart 2
AX2 = Plt.subplot (212) # Create a child 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))
    Plt.sca (AX1)   #❷# Select sub Figure 2 of chart 1
    Plt.plot (x, Np.sin (i*x))
    Plt.sca (AX2)  # Select Figure 2 's Sub 2
    Plt.plot (x, Np.cos (i*x))
Plt.show ()

display Chinese in a chart

The font used in the default configuration file for Matplotlib does not display Chinese correctly. There are several solutions available to allow the chart to display Chinese correctly. Specify the font directly in your program. Modify the configuration dictionary Rcparams at the beginning of the program. Modify the configuration file.

object-oriented drawing

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

The standard process for creating a chart directly using artists is as follows: Create a Figure object create a variety of simple types by using Figure objects to create one or more axes or subplot objects that call Axies

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               # Create A ' axes ' instance in the figure
Ax.plot (X1, Y1, X2, Y2)                 # Create A line2d instance in the axes
Fig.show ()
Fig.savefig ("Test.pdf")

Reference:

"Python Science Computing" (numpy video ) matplotlib-beautifully plotted (quick Drawing) (object-oriented Drawing) (for system learning)

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

Matplotlib.pylab Quick Drawing

Matplotlib also provides a module called Pylab, which includes many functions commonly used in NumPy and pyplot modules to facilitate rapid computation and drawing by users, and is ideal for use in Ipython interactive environments. Here, load the Pylab module using the following method:

>>> Import Pylab as pl

1 Installing numpy and matplotlib

>>> Import NumPy
>>> numpy.__version__

>>> Import Matplotlib
>>> matplotlib.__version__

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

21 percent Line Chart & Scatter chart Line and scatter plots

2.1.10 percent line map plots (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
Pl.show () # show the "Plot on" screen

2.1.2 Scatter plot scatter plots

To change Pl.plot (x, y) to Pl.plot (x, y, ' o '), the blue version of the following figure

2.2 Landscaping Making things look pretty

2.2.1 Line colors Changing the lines color

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

2.2.2 Line Style changing

Dashed line: Plot (X,y, '--')

2.2.3 marker Style Changing the marker style

Blue Star 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.)
Pl.show () # show the "Plot on" screen

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

The procedure is very direct, in turn, the drawing can be:

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.)
Pl.show () # show the "Plot on" 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 right ', ' upper left ', ' center ', ' lower left ', ' lower right '.

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

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, a] 

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: info-contact@alibabacloud.com 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.