Basic operation tutorial for drawing using numpy + matplotlib, numpymatplotlib

Source: Internet
Author: User

Basic operation tutorial for drawing using numpy + matplotlib, numpymatplotlib

Brief Introduction

Matplotlib is a python-based 2D image library. It can be used in python scripts to easily draw line charts, histograms, power spectral charts, scatter charts, and other commonly used charts with simple syntax. For more information, see the official matplot website.

Numpy (Numeric Python) is an extension of python Numeric operations that imitates matlab. It provides many advanced numerical programming tools, such as matrix data types and vector processing, and a precision library. It was designed for strict digital processing. It is said that since his appearance, NASA has handed over a lot of work originally done with fortran and matlab to numpy, it can be seen that it is powerful... His official website is here, and the specific information is in it.

Install

$sudo apt-get install python-matplotlib$sudo apt-get install python-numpy

(Good luck ~)

Use

Matplotlib can be used in scripts, but it will be more dazzling if it is used in ipython (directly adding the-pylab parameter can avoid the package import process ), it also provides functions similar to Matlab/Mathematica, real-time input, and real-time output. I personally think that he imitates Matlab/Mathematica, but it is indeed easier to program than the former.

In many cases, matplot needs to be used together with the numpy package. I don't want to separate the numpy package. I just need to mention it when using it. Note that the numpy package is usually imported as follows:

import numpy as np

It will give him an alias named np, And this is almost a convention.

In python or ipython, enter help (* functions to be searched *) (of course, you must first import the following package ).

First image

Package to be imported:

import numpy as npfrom pylab import *

First function Image

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)C,S = np.cos(X), np.sin(X)plot(X,C)plot(X,S)show()

Those who have the foundation of matlab are certainly not unfamiliar... Yes, the combination of the two modules is almost the same as that of matlab ..

1. Usenp.linspaceMethod to generate an array X, which is from$-\pi$Start$\pi$An array containing a total of 256 elements. The endpoint parameter indicates whether to include the first and end endpoints (the value is True or False, and the first letter must be in upper case ....). Of course, this array is a normal array, which is no different from other arrays.

2. Usenp.cos()Andnp.sin()The method is used in array X to calculate each element in array X and generate a result array. (Skip the iteration process ).

3. Call the plot method of pylab. The first parameter is the X-axis array, and the second parameter is the y-axis array. This will generate a default chart. (Not immediately displayed)

4. Of course, call the show method to display the chart.

5. Results:

The chart name is figure1. There are several buttons on the left, which are very useful. The bottom right corner of the chart displays the left of the current mouse, which is also very convenient.

Chart layout and coordinate distribution

Every chart is in a figure. We can use the following command to generate an empty figure:

figure(figsize=(8,6), dpi=80)

The parameter sequence is not required here, but the parameter name must be added, because it distinguishes each parameter according to the parameter name. It is a function different from the C language type. The figsize parameter indicates the aspect ratio of figure, and dpi indicates the length of each part. For example, the image is 640xx.

A window will appear immediately after the command is output, and all the subsequent plot commands will be immediately displayed in this window without entering the show command.

A figure can also display multiple charts. We can use the following function to split a figure:

subplot(3,4,6)

In this way, the current figure is divided into three rows and four columns, and the first of them is activated, that is, 6th rows and 2nd columns. In the future, the plot is generated in this subtable. If you need to replace it, You can re-enter the subplot command to determine its new location.

In addition, if we are not satisfied with the chart display range, we can also directly adjust the chart coordinate range:

xlim(-4.0,4.0)ylim(-1.0,1.0)

This indicates that the range of the X axis is from-4 to 4, and that of the Y axis is from-1 to 1. Of course, if you want to modify it, you can use the min and max methods of the numpy array. For exampleX.min() Such a thing.

If you are not satisfied with the density displayed by the coordinates, we can adjust the annotation points:

xticks(np.linspace(-4,4,9,endpoint=True))yticks(np.linspace(-1,1,5,endpoint=True))

For xticks and yticks, we can actually input any array, which is just an ascending series quickly generated by numpy for convenience.

Of course, we can also name annotation points as follows:

xticks([1,2,3,4,5],['one','two','three','four','five'])

The effect is also very good, so you don't need to map it. Note that the LaTex syntax can also be supported here. You can reference LaTex between two $ S. (About LaTex)

Here is also a tip, that is, if you want to not display the annotation, we can directly assign an empty array to xticks.

Change color and line width

We can use the following method to specify the color and line width when drawing a plot:

plot(X, C, color='#cadae3', linestyle='-',linewidth=1.3, marker='o', markerfacecolor='blue', markersize=12,)

Similarly, the order of parameters here is not important, and names are important.

The color parameter can specify the RGB color or use some default names, such as red blue.

The linestyle parameter specifies the line style. For details, refer to the following style:

Parameters Style
'-' Solid line
'-' Dotted Line
'-.' Line-point
':' Dotted Line

The linewidth parameter specifies the line width, which is a floating point number.

The marker parameter specifies the scatter style. For details, refer to the following style:

Parameters Style
'.' Solid point
'O' Circle
',' One pixel
'X' Cross
'+' Cross
'*' Asterisk
'^ ''V'' <''>' Triangle (upper left and lower right)
'1' 2' '3' '4' Three-digit number (upper-lower-left)

The markerfacecolor parameter specifies the marker color.

The markersize parameter specifies the marker size.

In this way, you can basically customize any line chart or scatter chart style.

Moving axis

This section is a little complicated. I don't want to know more about strange function calls. Let's record the usage and principles first:

ax = gca()ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')ax.xaxis.set_ticks_position('bottom')ax.spines['bottom'].set_position(('data',0))ax.yaxis.set_ticks_position('left')ax.spines['left'].set_position(('data',0))

We know that a chart has four axes: top, bottom, and left. Here we adjust the color of the axis on the right and top to transparent, and then set the bottom to the position where the Y axis data is 0, set the data on the left side to 0 on the X axis. In this way, we can adjust the axis line according to the position we want.

For example, the following official code:

# -----------------------------------------------------------------------------# Copyright (c) 2015, Nicolas P. Rougier. All Rights Reserved.# Distributed under the (new) BSD License. See LICENSE.txt for more info.# -----------------------------------------------------------------------------import numpy as npimport matplotlib.pyplot as pltplt.figure(figsize=(8,5), dpi=80)ax = plt.subplot(111)ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')ax.xaxis.set_ticks_position('bottom')ax.spines['bottom'].set_position(('data',0))ax.yaxis.set_ticks_position('left')ax.spines['left'].set_position(('data',0))X = np.linspace(-np.pi, np.pi, 256,endpoint=True)C,S = np.cos(X), np.sin(X)plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")plt.xlim(X.min()*1.1, X.max()*1.1)plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])plt.ylim(C.min()*1.1,C.max()*1.1)plt.yticks([-1, 0, +1], [r'$-1$', r'$0$', r'$+1$'])plt.show()

The result is:

Legends and annotations

The legend is very simple and the following code can be used:

plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")legend(loc='upper left')

You can specify the label attribute in the plot, and call the legend function to determine the legend position. Generally, the parameter is 'Upper left.

Annotation is a little troublesome. It is complicated to use the annotate command. I don't want to read it for the time being. Just paste a complete piece of code and:

# -----------------------------------------------------------------------------# Copyright (c) 2015, Nicolas P. Rougier. All Rights Reserved.# Distributed under the (new) BSD License. See LICENSE.txt for more info.# -----------------------------------------------------------------------------import numpy as npimport matplotlib.pyplot as pltplt.figure(figsize=(8,5), dpi=80)ax = plt.subplot(111)ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')ax.xaxis.set_ticks_position('bottom')ax.spines['bottom'].set_position(('data',0))ax.yaxis.set_ticks_position('left')ax.spines['left'].set_position(('data',0))X = np.linspace(-np.pi, np.pi, 256,endpoint=True)C,S = np.cos(X), np.sin(X)plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")plt.xlim(X.min()*1.1, X.max()*1.1)plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],  [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])plt.ylim(C.min()*1.1,C.max()*1.1)plt.yticks([-1, +1],  [r'$-1$', r'$+1$'])t = 2*np.pi/3plt.plot([t,t],[0,np.cos(t)],  color ='blue', linewidth=1.5, linestyle="--")plt.scatter([t,],[np.cos(t),], 50, color ='blue')plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',  xy=(t, np.sin(t)), xycoords='data',  xytext=(+10, +30), textcoords='offset points', fontsize=16,  arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))plt.plot([t,t],[0,np.sin(t)],  color ='red', linewidth=1.5, linestyle="--")plt.scatter([t,],[np.sin(t),], 50, color ='red')plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',  xy=(t, np.cos(t)), xycoords='data',  xytext=(-90, -50), textcoords='offset points', fontsize=16,  arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))plt.legend(loc='upper left', frameon=False)plt.savefig("../figures/exercice_9.png",dpi=72)plt.show()

:

Still very high-energy...

Summary

The above is all about this article. I hope this article will help you learn or use python. If you have any questions, please leave a message, thank you for your support.

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.