Python Scientific Computing--matplotlib

Source: Internet
Author: User
Tags sca

Matplotlib

python科学计算系列

Matplotlib is Python's most famous drawing library, which provides a complete set of command APIs similar to those of MATLAB, making it ideal for interactive 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.
Gallery The address of the display page

Simple Introduction

This content is from Pyplot_tutorial official documents

    • Plt.plot ()

      You may wonder why you set the Plt.plot ([1,2,3,4]) and the y-axis becomes the 1-4,x axis 1-3? This is because, there is a reason to call the rules ! Matplotlib default to only a set of list data is the Y value, and the x-axis is automatically generated. Because the Python range defaults from 0 and has the same length as the y axis, the x-axis data is [0,1,2,3]. Plt.ylabel (' Some numbers '), what is this, do not explain it.

    • Officials say the plot () method is very bull and accepts any number of data:


      Then, you think again. This time Plt.plot ([1,2,3,4], [1,4,9,16], ' ro ') is what. So, for the plot () method, there is a third parameter that sets the color and the graph type. The specific is inherited from Matlab, the default is ' B '-a solid blue line. Here, Red circle ' ro ' – too image, easy to remember.
      The following example uses arrays in a command to plot different styles of plot, and to look at it and understand it.

    • Control lines – see Matplotlib.lines for details

    • A picture of a multi-character figure –subplot ()

      • Let's introduce the subplot () function of Matplotlib.pylab with a picture:
      • Create two sub-graphs
    • Text on a horizontal axis

以上内容太费劲,不够简单粗暴

Quick Draw
  • Understand a few concepts first

    • Figure
      The whole figure (marked as the outer red box). The figure keeps track of the Axes.
    • Axes
      This is a think of as ' a plot ', it's the region of the the image with the data space (marked as the inner blue box). A given figure can contain many Axes, but a given Axes object can is only is in one figure. The Axes contains (or three in the case of 3D) axis objects (being aware of the difference between Axes and axis)
    • Axis
    • x label, y label, title
  • Pyplot Subpackage, Haven easiest-to-create a new figure was with Pyplot
    Matplotlib's Pyplot Sub-Library provides a mapping API similar to MATLAB, allowing users to quickly draw 2D charts.
  • Pylab Module
    Matplotlib also provides a module called Pylab, which includes many of the functions commonly used in numpy and Pyplot, allowing users to quickly calculate and draw, and can be used for fast, interactive use in Ipython.
  • Fuzzy use to get started again

    • First, then detailed analysis
    • A library of quick drawing functions in matplotlib can be loaded with the following statement:

      import matplotlib.pyplot as plt
    • The next call to figure creates a drawing object and makes it the current drawing object

      plt.figure(figsize=(8,4))       

      The Figsize parameter lets you specify the width and height of the drawing object in inches, and the DPI parameter specifies the resolution of the drawing object, which is the number of pixels per inch, and the default value is 80. So the chart window created in this example has a width of 8*80 = 640 pixels.
      You can also directly draw directly from the next plot function without creating a drawing object, and Matplotlib will automatically create a drawing object.
      If you need to draw multiple charts at the same time, you can pass an integer argument to the figure to specify the ordinal of the icon, and if the drawing object of the specified ordinal already exists, the new object will not be created, but only make it the current drawing object.

    • The following two lines of the program draw in the current drawing object by calling the plot function:

      Plt.plot (x,y,label= " i n ( 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, the matplotlib uses the mathematical formula drawn by the inner latex engine.
        • Color: Specify the colors of the curve
        • LineWidth: Specify the width of the curve
        • ' B – ' specifies the color and linetype of the curve
    • Next, you set the various properties of the drawing object through a series of functions:
      • Xlabel/ylabel: Set the text of the x-axis/y Axis
      • Title: Set the caption of the chart
      • Ylim: Setting the range of the y-axis
      • Legend: Display diagram
    • The last Call to Plt.show () displays all the drawing objects created.
  • Save Chart
    You can also call Plt.savefig () to save the current figure object as an image file, and the image format is determined by the image file extension. The following program saves the current chart as "Test.png", and the DPI parameter specifies that the image has a resolution of 120, so the output image has a width of "8x120 = 960" pixels.

    plt.savefig("test.png",dpi=120)

    You don't actually need to call show () to display the chart, you can save the chart as an image file directly with Savefig (). Using this method, it is easy to write a program for batch output charts.

  • Draw a multi-axis diagram
    A drawing object (figure) can contain more than one axis (axis), which is used to represent a drawing area in matplotlib and can be interpreted as a sub-graph. In the first example above, the drawing object includes only one axis, so only one axis (Axes) is displayed. You can use the subplot function to quickly draw a chart with multiple axes. The subplot function is called in the following form:

     subplot(numRows, numCols, plotNum)

    Subplot divides the entire drawing area into numrows rows and numcols column sub-regions and then numbers each sub-region from left to right, top to bottom, and the upper-left sub-region 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.

      • The following program creates 3 rows and 2 columns with a total of 6 axes, and sets different background colors for each axis through the AXISBG parameter.

        For IDX, color in enumerate ("Rgbyck"):
        Plt.subplot (320+idx+1, Axisbg=color)
        Plt.show ()

      • If you want an axis to occupy an entire row or column, you can call subplot as follows:

        plt.subplot(221) # 第一行的左图plt.subplot(222) # 第一行的右图plt.subplot(212) # 第二整行plt.show()

    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.

  • Subplot () returns the Axes object that it creates, which you can save with a variable, and then alternate with SCA () to make them the current axes object, and call plot () to draw in it. 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. The following procedure demonstrates how to draw a curve in a different sub-diagram of a different chart in turn. The

    • First creates two charts with a figure (), with a sequence number of 1 and 2, respectively. Then two sub-graphs are created up and down in chart 2 and saved with variables Ax1 and ax2.

        import numpy as Npimport Matplotlib.pyplot as Pltplt.figure (1) # Create chart 1plt.figure (2) # Create chart 2ax1 = Plt.subplo T (211) # Create a sub-figure in diagram 2 1ax2 = Plt.subplot (212) # Create a sub-figure in chart 2 2x = np.linspace (0, 3, +)  
    • In the loop, first call figure (1) Make chart 1 the current chart and draw in it. Then call SCA (AX1) and SCA (AX2) to make the sub-diagram Ax1 and ax2 the current sub-diagram, and draw in it. When they become the current sub-diagram, the chart 2 that contains them is also automatically the current chart, so you do not need to call figure (2) to switch between the two sub-plots in Chart 1 and chart 2, and gradually add a new curve

        for I in Xrange (5): Plt.figure (1) # Select Chart 1 plt.plot (x, Np.exp (I*X/3)) Plt.sca (AX1) # Select the sub-figure of Chart 2 1 plt.plot (x, Np.sin (i*x)) Plt.sca (ax2 # 2 Plt.plot (x, Np.cos (i*x)) plt.show ()  

  • Select Figure 2
  • Axis settings
    Axis containers include tick marks for axes, tick labels, coordinate grids, and axis titles. The scale includes the main scale and the sub-scale, respectively, by the Get_major_ticks () and the Get_minor_ticks () method. Each tick mark is a XTick or Ytick object that includes the actual tick marks and tick labels. For easy access to tick marks and text, the Axis object provides the Get_ticklabels () and Get_ticklines () methods to directly obtain tick labels and tick marks.

    • The following example plots and obtains the X axis object of the current sub-graph axis:
Not to be continued

Python Scientific Computing--matplotlib

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.