Matplotlib Basic Usage

Source: Internet
Author: User
Keywords matplotlib matplotlib tutorial matplotlib python
Matplotlib is a drawing tool similar to MATLAB in Python. You can quickly get started with Matplotlib if you are familiar with MATLAB.

1. Meet Matploblib
1.1 Figure
Before any drawing, we need a Figure object, which can be understood as we need a drawing board to start drawing.

import matplotlib.pyplot as plt
fig = plt.figure()

1.2 Axes
After having the Figure object, we still need the axis before drawing. If there is no axis, there is no datum, so we need to add Axes. It can also be understood as paper that can really be painted.

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set(xlim=[0.5, 4.5], ylim=[-2, 8], title='An Example Axes',
       ylabel='Y-Axis', xlabel='X-Axis')
plt.show()

Added an Axes to a picture, and then set the value range of the Axes X axis and Y axis (these settings are not mandatory, we will talk about these settings later), the effect is as follows:

For the above figure.add_subplot(111) is to add Axes, the explanation of the parameters is to generate an Axes object at the first position of the first row and first column of the artboard to prepare for painting. Axes can also be generated by fig.add_subplot(2, 2, 1). The first two parameters determine the division of the panel, such as 2, 2 will divide the entire panel into 2 * 2 squares, the third parameter is taken The range of values is [1, 2*2] which indicates the number of Axes. As the following example:

fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(224)

1.3 Multiple Axes
It can be found that the addition of Axes above seems to be a little weak, so the following method is provided to generate all Axes at once:

fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0,0].set(title='Upper Left')
axes[0,1].set(title='Upper Right')
axes[1,0].set(title='Lower Left')
axes[1,1].set(title='Lower Right')

fig is also a familiar artboard, axes has become our commonly used two-dimensional array form of access, which is extra easy to use when drawing in a loop.

1.4 Axes Vs .pyplot
I believe that many people have seen the following code, which is very simple and easy to understand, but the following painting method is only suitable for simple drawing, and the drawing is quickly drawn. When dealing with complex drawing work, we still need to use Axes to complete the painting.

plt.plot([1, 2, 3, 4], [10, 20, 25, 30], color='lightblue', linewidth=3)
plt.xlim(0.5, 4.5)
plt.show()

2. Basic drawing 2D
2.1 Line
The plot() function draws a series of points, and connects them with lines. Look at the example:

x = np.linspace(0, np.pi)
y_sin = np.sin(x)
y_cos = np.cos(x)

ax1.plot(x, y_sin)
ax2.plot(x, y_sin,'go--', linewidth=2, markersize=12)
ax3.plot(x, y_cos, color='red', marker='+', linestyle='dashed')

Paint on the three Axes above. Plot, the first two parameters are x-axis and y-axis data. The third parameter of ax2 is a MATLAB-style drawing, corresponding to the color, marker, and line type on ax3.

In addition, we can draw by keyword parameters, as the following example:

x = np.linspace(0, 10, 200)
data_obj = {'x': x,
            'y1': 2 * x + 1,
            'y2': 3 * x + 1.2,
            'mean': 0.5 * x * np.cos(2*x) + 2.5 * x + 1.1}

fig, ax = plt.subplots()

#Fill the color between the two lines
ax.fill_between('x','y1','y2', color='yellow', data=data_obj)

# Plot the "centerline" with `plot`
ax.plot('x','mean', color='black', data=data_obj)

plt.show()

It is found that in the above drawing, only strings are passed in the data part. These strings are for a keyword in this data_obj. When drawing in this way, the data corresponding to the keyword will be found in the data passed to data To draw.


2.2 Scatter chart
Only draw dots, but do not connect them with lines.

x = np.arange(10)
y = np.random.randn(10)
plt.scatter(x, y, color='red', marker='+')
plt.show()

2.3 Bar chart
There are two types of bar charts, one is horizontal and the other is vertical. See the following example:

np.random.seed(1)
x = np.arange(5)
y = np.random.randn(5)

fig, axes = plt.subplots(ncols=2, figsize=plt.figaspect(1./2))

vert_bars = axes[0].bar(x, y, color='lightblue', align='center')
horiz_bars = axes[1].barh(x, y, color='lightblue', align='center')
#Draw a line horizontally or vertically
axes[0].axhline(0, color='gray', linewidth=2)
axes[1].axvline(0, color='gray', linewidth=2)
plt.show()

The bar graph also returns an array of Artists, corresponding to each bar. For example, the size of the Artists array in the above figure is 5, we can use these Artists to change the style of the bar graph, as in the following example:

fig, ax = plt.subplots()
vert_bars = ax.bar(x, y, color='lightblue', align='center')

# We could have also done this with two separate calls to `ax.bar` and numpy boolean indexing.
for bar, height in zip(vert_bars, y):
    if height <0:
        bar.set(edgecolor='darkred', color='salmon', linewidth=3)

plt.show()

2.4 Histogram
The histogram is used to count the frequency or frequency of data. There are various parameters that can be adjusted.

np.random.seed(19680801)

n_bins = 10
x = np.random.randn(1000, 3)

fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, ax3 = axes.flatten()

colors = ['red','tan','lime']
ax0.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors)
ax0.legend(prop={'size': 10})
ax0.set_title('bars with legend')

ax1.hist(x, n_bins, density=True, histtype='barstacked')
ax1.set_title('stacked bar')

ax2.hist(x, histtype='barstacked', rwidth=0.9)

ax3.hist(x[:, 0], rwidth=0.9)
ax3.set_title('different sample sizes')

fig.tight_layout()
plt.show()
The density in the parameter controls whether the Y axis is a probability or a quantity, corresponding to the first variable returned. The histtype controls the style of the histogram. The default is ‘bar’. For multiple bars, they are presented next to each other as in sub-picture 1. ‘barstacked’ is stacked together, as in sub-pictures 2 and 3. rwidth controls the width, so that some gaps can be left, compare Figures 2 and 3. Figure 4 is when there is only one data.



2.5 Pie chart
labels ='Frogs','Hogs','Dogs','Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e.'Hogs')

fig1, (ax1, ax2) = plt.subplots(2)
ax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True)
ax1.axis('equal')
ax2.pie(sizes, autopct='%1.2f%%', shadow=True, startangle=90, explode=explode,
    pctdistance=1.12)
ax2.axis('equal')
ax2.legend(labels=labels, loc='upper right')

plt.show()

The pie chart automatically draws the pie based on the percentage of the data. labels is the label of each block, as shown in subfigure 1. autopct=%1.1f%% means that the formatted percentage is output accurately, explode, highlight some blocks, and the effect of different values is different. pctdistance=1.12 percentage distance from the center of the circle, the default is 0.6.
2.6 Box chart
In order to focus on how to draw the picture, the data processing part is omitted. The shape of data is (n, ), and the shape of data2 is (n, 3).

fig, (ax1, ax2) = plt.subplots(2)
ax1.boxplot(data)
ax2.boxplot(data2, vert=False) #Control direction
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.