Drawing artifact-matplotlib Getting Started

Source: Internet
Author: User

This time, let's use a very famous and very interesting thing to do today's task, yes it is jupyter.

First, install the Jupyter

Before Matplotlib get started, install Jupyter first. Only the most convenient and quick installation method is available here:pip install Jupyter.

I've already installed it here.

Starting Jupyter is also very simple:jupyter notebook

After executing the command, automatically start the service and automatically open the browser, jupyter the long

Find the directory you want, top right corner new-->python3 create a new Jupyter file that can execute Python3 code

The new file looks like this. Although each cell is independent, the next cell can reference a variable from the previous cell

Add: Jupyter Some common shortcut commands

Ctrl+enter executing the current cell
Shift+enter executes the current cell and jumps to the next cell
DD Delete current cell
A build a cell up
b Build a cell down
esc+m/m switching the current cell to Markdown mode
esc+y/y to switch the current cell to code mode
ESC+L/L Show/Hide the line number of the current cell
o Close or open the output of the current cell
Shift-Select multiple cells
Shift+m Merging multiple cells

Ii. Introduction to Matplotlib

What is Matplotlib?

The official explanations are: Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy fo Rmats and interactive environments across platforms. You can generate plots, histograms, power spectra, bar charts, Errorcharts, Scatterplots, etc., with just a few lines of C Ode.

Matplotlib is a Python 2D drawing library that generates publishing quality-level graphics in a variety of hard-copy formats and cross-platform interactive environments. With just a few lines of code, you can generate plots, histograms, power spectra, bar charts, error plots, scatter plots, and more.

0. Install dependent libraries: Matplotlib, NumPy (pip install *)

NumPy is an open-source numerical extension repository for Python. This tool can be used for large matrix data type processing, vector processing, and precision operations.

(In a whisper, these two are two of machine learning musketeers)

Kind

As you can see, the code, although only 3 lines, is very intuitive to draw a line graph.

data = Np.arange (100, 200): Generates an array of integers between 100-200 and its value is [100,101...200]

Plt.plot (data): The above array is drawn, corresponding to the y-axis of the graph, and the matplotlib itself sets the x-axis of [0,100] by default, so that its one by one corresponds

Plt.show (): Show the picture

1. Draw a Line chart
Import Matplotlib.pyplot as Pltplt.plot (['-R') plt.plot ([': G  ') plt.plot (['y') plt.show ()

Plot accepts three parameters, the first parameter is an array, as the value of the x-axis, the second parameter is an array, as the value of the y-axis, and the third parameter indicates that the line chart is an attribute, the composition and color of the graph, such as the following: Red straight lines, green dots, yellow lines.

2. Plot scatter plots
ImportMatplotlib.pyplot as PltImportNumPy as NpN= 20Plt.scatter (Np.random.rand (N)* 100, Np.random.rand (N)*100, C='R', s=100, alpha=0.5) Plt.scatter (Np.random.rand (N)* 100, Np.random.rand (N)*100, C='y', s=200, alpha=0.8) Plt.scatter (Np.random.rand (N)* 100, Np.random.rand (N)*100, C='b', s=300, alpha=0.5) plt.show ()

This image contains three sets of data, each containing 20 random coordinates. The parameter C represents the color of the point, S is the size of the point, and Alpha is the transparency

Scatter plot scatter chart detailed documentation, reference: Https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html#matplotlib.pyplot.scatter

3. Pie chart
ImportMatplotlib.pyplot as PltImportNumPy as Nplabels= ['Suger','Popo','python','Java','Ruby','C #']data= Np.random.rand (6) * 100plt.pie (data, labels=labels, autopct='%1.1f%%') Plt.axis ('Equal') Plt.legend () plt.show ()

Data is a set of random values containing 6 data, the labels in the diagram are specified by labels, autopct specifies the precision format of the numeric values, Plt.axis (' equal ') sets the coordinate axis size, and Plt.legend () indicates the plot to be drawn.

Pie Plot pie chart detailed reference: Https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pie.html?highlight=pie#matplotlib.pyplot.pie

4. Bar chart
ImportMatplotlib.pyplot as PltImportNumPy as NpN= 7x=Np.arange (N) data= Np.random.randint (low=0, high=100, size=N) Colors= Np.random.rand (n * 3). Reshape (n,-1) Labels= ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']plt.title ('Weekday Data') Plt.bar (x, data, Alpha=0.8, Color=colors, tick_label=labels) plt.show ()

# This diagram shows a set of results with 7 random values, each of which is a random number of [0, 100]
# Their colors are also generated by random numbers. Np.random.rand (n * 3). Reshape (n,-1) represents the number of random numbers (n x 3) and then assembles them into 7 rows, then each row is three digits, which corresponds to the three components of the color
# TITLE Specifies the caption of the graphic, labels specifies the label, and Alpha is the transparency

Bar Drawing Bar Official document: Https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html?highlight=bar#matplotlib.pyplot.bar

5. Histogram
Import Matplotlib.pyplot as Plt Import   for in [4000,= ['3k'4k  '5k'= [0, +, +, +, 4000, +] Plt.hist (data, bins=bins, label=labels) plt.legend () plt.show ()

# [Np.random.randint (0, N, N) for n in [4000,X]] generates an array of 3 arrays: The first array contains 3,000 random numbers, the range of which is [0, 3000]; Two arrays contain 4,000 random numbers whose range is [0, 4000]; The third array contains 5,000 random numbers, and the range of these random numbers is [0, X, x] .

# Bins Sets the bounds of the histogram. [0, +, X, S, s, +, 4000, x] set 7 boundaries, such as: the first boundary is [0,100], there is a stronghold, the boundary-bound picture will be drawn in it

# All three groups of data have 3000 or less data, the figures below 3000 are also data, [3000,4000] data base is not 3k, while the [4000,5000] Stronghold is only 5k data left.

hist more usage of histogram plotting: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html?highlight=hist#matplotlib.pyplot.hist

Above, at present we have learned to draw simple line graph, scatter chart, pie chart, bar chart and histogram, obviously this is just fur, truly breathtaking figure, do in Matplotlib Gallery.

An example is extracted here:

ImportNumPy as NPImportMatplotlib.pyplot as PltImportMatplotlib.gridspec as GRIDSPECW= 3Y, X= np.mgrid[-w:w:100j,-w:w:100j]u= -1-x**2 +YV= 1 + x-y**2 Speed= np.sqrt (U*u + v*V) FIG= Plt.figure (figsize= (7, 9)) GS= Gridspec. Gridspec (nrows=3, ncols=2, height_ratios=[1, 1, 2])#Varying density along a streamlineAx0 =Fig.add_subplot (gs[0, 0]) Ax0.streamplot (X, Y, U, V, density=[0.5, 1]) Ax0.set_title ('Varying Density')#Varying color along a streamlineAx1 = Fig.add_subplot (gs[0, 1]) STRM= Ax1.streamplot (X, Y, U, V, Color=u, linewidth=2, cmap='Autumn') Fig.colorbar (strm.lines) ax1.set_title ('Varying Color')#Varying line width along a streamlineAX2 = Fig.add_subplot (gs[1, 0]) LW= 5*speed/Speed.max () ax2.streamplot (X, Y, U, V, density=0.6, color='k', linewidth=LW) Ax2.set_title ('Varying Line Width')#controlling the starting points of the streamlinesseed_points = Np.array ([-2,-1, 0, 1, 2,-1], [-2,-1, 0, 1, 2, 2]]) ax3= Fig.add_subplot (gs[1, 1]) STRM= Ax3.streamplot (X, Y, U, V, Color=u, linewidth=2, CMap='Autumn', start_points=seed_points. T) Fig.colorbar (strm.lines) ax3.set_title ('Controlling starting Points')#Displaying The starting points with blue symbols.Ax3.plot (Seed_points[0], seed_points[1],'Bo') Ax3.axis (-W, W,-W, W))#Create a maskMask = Np.zeros (U.shape, dtype=bool) mask[40:60, 40:60] =trueu[:20,: 20] =Np.nanu= Np.ma.array (U, mask=mask) ax4= Fig.add_subplot (gs[2:, :]) Ax4.streamplot (X, Y, U, V, color='R') Ax4.set_title ('Streamplot with masking') Ax4.imshow (~mask, Extent= (-W, W, W, W), alpha=0.5, interpolation='Nearest', cmap='Gray', aspect='Auto') Ax4.set_aspect ('Equal') Plt.tight_layout () plt.show ()

Drawing artifact-matplotlib Getting Started

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.