Matplotlib for Python Developers

Source: Internet
Author: User
Tags explode sin timedelta

This tutorial is also very good, http://reverland.org/python/2012/09/07/matplotlib-tutorial/

can also refer to the official website gallery,http://matplotlib.org/gallery.html

Do data analysis, the first is to be familiar with and understand the data, so it is very important to master a visual tool of the hand, otherwise there is no basic perceptual knowledge of the data, how to carry out the next design

Getting Started with Matplotlib

Let's look at a simple example, plot, which draws the line

Draw the line, need to give the coordinates of the point on the outlet, then Matplotlib will automatically connect the point to the line

In [2]: x = Range (6)
In [3]: Plt.plot (x, [Xi**2 for Xi in X])

You can see that the plot parameter is a list of two lists, which distributes the coordinates of the x and Y axes.

You can see that the lines here are not very smooth, because the point granularity produced by range is thicker and the Y value is generated using the list comprehension

So try to use NumPy's Arange (x, y, z) function here.

The advantage is that the granularity can be smaller, and the key is to return an array of numpy, which can be directly performed by vector or matrix operations, as follows

In [3]: x = Np.arange (1, 5)
In [4]: Plt.plot (x, x*1.5, X, x*3.0, X, x/3.0)

You can draw multiple lines with plot

Grid, axes, and labels

Open Grid

In [5]: Plt.grid (True)

The default is to automatically generate a range of values on the X and Y axes, such as the diagram above,

In [5]: Plt.axis () # shows the current axis limits values
OUT[5]: (1.0, 4.0, 0.0, 12.0)
respectively, [Xmin, Xmax, ymin, ymax], so look at the x axis is from 1 to 4,y axis is from 0 to 12

Change the value range,
In [6]: Plt.axis ([0, 5,-1, +]) # set new axes limits

You can also add lable to the x and Y axes,

In [2]: Plt.plot ([1, 3, 2, 4])
In [3]: Plt.xlabel (' The X axis ')
In [4]: Plt.ylabel (' The Y axis ')

Titles and Legends

Add title to the entire graph

In [2]: Plt.plot ([1, 3, 2, 4])
In [3]: Plt.title (' simple plot ')

You can also add an icon to each line, legend

In [3]: x = Np.arange (1, 5)
In [4]: Plt.plot (x, x*1.5, label= ' Normal ')
In [5]: Plt.plot (x, x*3.0, label= ' Fast ')
In [6]: Plt.plot (x, x/3.0, label= ' Slow ')
In [7]: Plt.legend ()

Specify a label for each line, and then call Legend () to display the diagram automatically

You can see the location of this diagram is not very good, blocking the diagram, you can specify the location by parameters

Legend (loc= ' upper left ')

LOC can pick the value, where best, is automatically found in the finest location

Saving plots to a file

Simplest, use the default settings
Plt.savefig (' Plot123.png ')

Two of these settings can determine the image size, figure size and the DPI

In [1]: Import matplotlib as Mpl
In [2]: mpl.rcparams[' figure.figsize ']
OUT[2]: [8.0, 6.0]
In [3]: mpl.rcparams[' savefig.dpi ']
OUT[3]: 100

An 8x6 inches figure with a results in a 800x600 pixels image, which is the default value

In [4]: Plt.savefig (' plot123_2.png ', dpi=200)

The resolution of this diagram becomes 1600x1200

decorate Graphs with Plot Styles

Markers and line Styles

The lines are all the same, but we can draw a variety of different lines.
Marker means the dots that form the line.

Plot () supports an optional third argument this contains a format string for each pair of X, Y arguments in the form of:
Plt.plot (X, Y, ' <format> ', ...)

Plot can be specified by a third string parameter, Colors,line styles,marker styles

The color of the line,

The style of the line,

The style of marker

You can use string format to represent all the style individually or in combination

In [3]: y = Np.arange (1, 3, 0.3)
In [4]: Plt.plot (y, ' cx--', y+1, ' Mo: ', y+2, ' kp-. ');

For example, the first line, C for Cyan Cyan, and X for marker style for x,--.

The usual string format is sufficient, but it can be more personalized with specific keyword parameters.

Handling X and Y ticks

The ticks on the X and Y axes are automatically generated, and this can be customized by xticks and yticks functions.

The arguments (in the form of lists) so we can pass to the function is:
? Locations of the Ticks
? Labels to draw at these locations (if necessary)

Can be defined, the location of each tick and the corresponding label (optional, do not specify the default display location)

In [2]: x = [5, 3, 7, 2, 4, 1]
In [3]: Plt.plot (x);
In [4]: Plt.xticks (Range (len (x)), [' A ', ' B ', ' C ', ' d ', ' e ', ' f ']);
In [5]: Plt.yticks (Range (1, 8, 2));

Specify both location and label on x-axis
Specify location for y-axis only

Plot Types

Many of the above are described in plot as an example, Matplotlib also provides many other types of graphs
The author of this picture is great, describing the use of all graphs

Histogram charts

Histograms are used to distribute discrete statistical data, and the entire data set, according to the range of values, is divided into classes called bins
Then count the number of data in each bin in the statistics

In [3]: y = np.random.randn (1000)
In [4]: Plt.hist (y);
In [5]: Plt.show ()

hist default is divided into 10 categories, that is, bins=10, that is, the value [ -4,4] on the 1000 random number, divided into 10 bins, statistics of the number of each data
We can see that this random function is a typical normal distribution.

We can change the value of bins,
In [6]: Plt.hist (y, 25);

Yes, divided into 25 bins

Error Bar Charts

In [3]: x = Np.arange (0, 4, 0.2)
In [4]: y = np.exp (-X)
In [5]: e1 = 0.1 * Np.abs (NP.RANDOM.RANDN (len (y)))
In [8]: E2 = 0.1 * Np.abs (NP.RANDOM.RANDN (len (y)))
In [9]: Plt.errorbar (x, Y, Yerr=e1, xerr=e2, fmt= '.-', capsize=0);

Draw each point at the same time, draw the error range at each point

It can also draw an asymmetric error,
In [All]: Plt.errorbar (x, Y, Yerr=[e1, E2], fmt= '.-');

Bar charts

Plt.bar ([1, 2, 3], [3, 2, 5]);

For bar, you need to set 3 parameters
Left start coordinate, height, width (optional, default 0.8)
So the above example, specify the starting point and the height parameter

Well, look at a complex example, bar graphs are typically used to compare multiple data values

In [3]: Data1 = 10*np.random.rand (5)
In [4]: Data2 = 10*np.random.rand (5)
In [5]: Data3 = 10*np.random.rand (5)
In [6]: E2 = 0.5 * Np.abs (NP.RANDOM.RANDN (len (data2)))
In [7]: Locs = Np.arange (1, Len (data1) +1)
In [8]: width = 0.27
In [9]: Plt.bar (locs, data1, width=width);
In [ten]: Plt.bar (Locs+width, data2, Yerr=e2, width=width, color= ' red ');
In [All]: Plt.bar (Locs+2*width, data3, width=width, color= ' green ');
in [n]: plt.xticks (locs + width*1.5, locs);

What you need to learn is how to specify the starting position of multiple bars, the LOC at the rear bar = loc + width of the previous bar
How to set the Ticks label so that it is in the middle of a set of bars, locs + width*1.5

Pie charts

The pie chart is very well understood and represents an ingredient

In [2]: Plt.figure (figsize= (3,3));
In [3]: x = [45, 35, 20]
In [4]: labels = [' Cats ', ' Dogs ', ' Fishes ']
In [5]: Plt.pie (x, labels=labels);

To a complex,
Add explode, which highlights some wedges, can be set explode to increase the offset the wedge from the center of the pie, that is, radius fraction
0 means no separation, the larger the distance from the pie center, the more you need to explicitly specify the explode for each wedges

Increase autopct, i.e. show specific proportions on wedges

In [2]: Plt.figure (figsize= (3,3));
In [3]: x = [4, 9, 21, 55, 30, 18]
In [4]: labels = [' Swiss ', ' Austria ', ' Spain ', ' Italy ', ' France ', ' Benelux ']
In [5]: explode = [0.2, 0.1, 0, 0, 0.1, 0]
In [6]: Plt.pie (x, Labels=labels, Explode=explode, autopct= '%1.1f%% ');

Scatter plots

Draw only points, not lines, to describe the relationship between the two variables, for example, to see if the variables are linear or non-linear before fitting the data.

In [3]: x = NP.RANDOM.RANDN (1000)
In [4]: y = np.random.randn (1000)
In [5]: Plt.scatter (x, y);

Specify a color by using S to specify Size,c.
Marker to refer to the shape of a point

In [7]: size = 50*NP.RANDOM.RANDN (1000)
In [8]: Colors = np.random.rand (1000)
In [9]: Plt.scatter (x, Y, s=size, c=colors);

Text inside figure, annotations, and arrows

For adding annotations,

Add text is simple, coordinates x, Y, content

Plt.text (x, y, text)

Example

In [3]: x = Np.arange (0, 2*np.pi,. 01)
In [4]: y = np.sin (x)
In [5]: Plt.plot (x, y);
In [6]: Plt.text (0.1, -0.04, ' sin (0) =0 ');

Annotate, easy to add annotations

Parameters
XY, the coordinates of the annotation need to be added
Xytext, the coordinates of the annotation itself
Arrowprops, types and properties of arrows

In [2]: y = [13, 11, 13, 12, 13, 10, 30, 12, 11, 13, 12, 12, 12, 11,12]
In [3]: Plt.plot (y);
In [4]: Plt.ylim (ymax=35); Increase the space of Y, otherwise the comment will not fit
In [5]: plt.annotate (' This spot must really\nmean something ',
Xy= (6, +), xytext= (8, 31.5), arrowprops=dict (facecolor= ' black ', shrink=0.05));

Obviously this arrow is ugly, the arrows can have many kinds of

In [2]: Plt.axis ([0, 10, 0, 20]);
In [3]: Arrstyles = ['-'-', ', '-', '-'-', ' <-', ' <-> ', ' fancy ', ' simple ', ' wedge ']
In [4]: For I, style in enumerate (arrstyles):
Plt.annotate (Style, xytext= (1, 2+2*i), xy= (4, 1+2*i), Arrowprops=dict (Arrowstyle=style));


In [5]: connstyles=["arc", "arc,anglea=10,arma=30,rad=15", "arc3,rad=.2", "arc3,rad=-.2", "angle", "angle3"]
In [6]: For I, style in enumerate (connstyles):
Plt.annotate ("", xytext= (6, 2+2*i), xy= (8, 1+2*i), arrowprops=dict (arrowstyle= ', Connectionstyle=style ');

Subplots

Above matplotlib, the default will help us create figure and subplot

Fig = Plt.figure ()
Ax = Fig.add_subplot (111)

We can actually create it explicitly, and the advantage is that we can draw multiple subplot in a figure

The parameters of which subplot,

Fig.add_subplot (NumRows, Numcols, Fignum)
-NumRows represents the number of rows of subplots to prepare
-Numcols represents the number of columns of subplots to prepare
-Fignum varies from 1 to numrows*numcols and specifies the current subplot (the one used now)

We're going to have numrowsxnumcols a subplot,fignum number.

In [2]: Fig = plt.figure ()
In [3]: Ax1 = Fig.add_subplot (211)
In [4]: Ax1.plot ([1, 2, 3], [1, 2, 3]);
In [5]: ax2 = Fig.add_subplot (212)
In [6]: Ax2.plot ([1, 2, 3], [3, 2, 1]);

Plotting Dates

Long date, directly on the axis, can't see

What do you think about painting?

Generates x-axis data and generates x-axis coordinates using Mpl.dates.drange

Import Matplotlib as Mpl
In [7]: Date2_1 = Dt.datetime (2008, 9, 23)
In [8]: Date2_2 = Dt.datetime (2008, 10, 3)
In [9]: Delta2 = Dt.timedelta (Days=1)
In [ten]: Dates2 = Mpl.dates.drange (Date2_1, date2_2, Delta2)

Generate y-axis coordinates randomly, draw Polt graph

In [all]: y2 = Np.random.rand (len (dates2))
in [n]: Ax2.plot_date (Dates2, y2, linestyle= '-');

The key steps come, we're going to set Xaxis's locator and formatter to show the time
First set the formatter,

In []: Datefmt = mpl.dates.DateFormatter ('%y-%m-%d ')
In []: Ax2.xaxis.set_major_formatter (DATEFMT)

Then set the locator,

In []: Daysloc = Mpl.dates.DayLocator ()
in [+]: Hoursloc = Mpl.dates.HourLocator (interval=6)
In []: Ax2.xaxis.set_major_locator (Daysloc)
In []: Ax2.xaxis.set_minor_locator (Hoursloc)

Note here that major and minor,major are large tick,minor are relatively small tick (default is null)
For example, date is a big tick, but want to see the fine point, so set a hour tick, but draw 24 too much, so interval=6, only draw 4
And formatter just set major, so minor is no label

Let's look at an example,

produces x-axis coordinates, y-axis coordinates, plot

In []: Date1_1 = Dt.datetime (2008, 9, 23)
In [all]: Date1_2 = Dt.datetime (2009, 2, 16)
In []: Delta1 = Dt.timedelta (days=10)
in [+]: dates1 = Mpl.dates.drange (Date1_1, date1_2, Delta1)
in [+]: y1 = Np.random.rand (len (dates1))
in [+]: ax1.plot_date (dates1, y1, linestyle= '-');

Set Locator
Major's Month,minor is week.

in [+]: Monthsloc = Mpl.dates.MonthLocator ()
In []: Weeksloc = Mpl.dates.WeekdayLocator ()
in [+]: Ax1.xaxis.set_major_locator (Monthsloc)
In [to]: Ax1.xaxis.set_minor_locator (Weeksloc)

Set Formatter

in [+]: monthsfmt = mpl.dates.DateFormatter ('%b ')
in [[]: Ax1.xaxis.set_major_formatter (MONTHSFMT)

Using LaTeX Formatting

This slightly diao

The start and the end of a mathtext string is $
The Python raw string needs R ', which means no escaping

Look directly at the example,

In [6]: Ax.text (2, 8, R "$ \mu \alpha \tau \pi \lambda \omega \tau \lambda \iota \beta $");
In [7]: Ax.text (2, 6, R "$ \lim_{x \rightarrow 0} \frac{1}{x} $");
In [8]: Ax.text (2, 4, r "$ A \ \leq \ b \ \leq \ c \ \rightarrow \ a \ \leq \ C $");
In [9]: Ax.text (2, 2, R "$ \sum_{i=1}^{\infty}\ x_i^2$");
In [ten]: Ax.text (4, 8, R "$ \sin (0) = \cos (\frac{\pi}{2}) $");
In [All]: Ax.text (4, 6, R "$ \sqrt[3]{x} = \sqrt{y}$");
In []: Ax.text (4, 4, R "$ \neg (a \wedge b) \leftrightarrow \neg a \vee \neg b$");
In []: Ax.text (4, 2, R "$ \int_a^b f (x) dx$");

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: 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.