Matplotlib Drawing Summary

Source: Internet
Author: User
Keywords matplotlib matplotlib tutorial matplotlib python
This article is used to sort out some common knowledge points of matplotlib in the learning process, which is convenient for searching.

MATLAB-like API
The easiest entry is to start with the MATLAB-like API, which is designed to be compatible with MATLAB drawing functions.

from pylab import *

from numpy import *
x = linspace(0, 5, 10)
y = x ** 2

figure()
plot(x, y,'r')
xlabel('x')
ylabel('y')
title('title')


Create a sub-picture, select the color and punctuation symbol used for drawing:

subplot(1,2,1)
plot(x, y,'r--')
subplot(1,2,2)
plot(y, x,'g*-');


linspace represents 10 points between 0 and 5, and the third parameter of plot represents the color and style of the line

The benefit of this type of API is that it can save you a lot of code, but we do not encourage it to be used for complex charts. When dealing with complex charts, the matplotlib object-oriented API is a better choice.

matplotlib object-oriented API
The method of using the object-oriented API looks very similar to the previous example, the difference is that we do not create a global instance, but save the reference of the new instance in the fig variable, if we want to create a new coordinate in the figure For axis instances, just call the add_axes method of the fig instance:

import matplotlib.pyplot as plt
from pylab import *
x = linspace(0, 5, 10)
y = x ** 2

fig = plt.figure()

axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)

axes.plot(x, y,'r')

axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')

plt.show()


Although more code will be written, the advantage is that we have full control over the drawing of the chart, and we can easily add an additional axis to the chart:

import matplotlib.pyplot as plt
from pylab import *
x = linspace(0, 5, 10)
y = x ** 2

fig = plt.figure()

axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes

axes.plot(x, y,'r')

axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')

# insert
axes2.plot(y, x,'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('insert title');

plt.show()


If we don't care about the position of the coordinate axis in the figure, then we can use matplotlib's layout manager. My favorite is subplots, which are used as follows:

import matplotlib.pyplot as plt
from pylab import *
x = linspace(0, 5, 10)
y = x ** 2

fig, axes = plt.subplots(nrows=1, ncols=2)

for ax in axes:
    ax.plot(x, y,'r')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_title('title')

fig.tight_layout()


plt.show()


Chart size, aspect ratio and DPI

When creating the Figure object, use the figsize and dpi parameters to set the chart size and DPI, and create a 800*400 pixel, 100 pixel per inch figure:

fig = plt.figure(figsize=(8,4), dpi=100)


<matplotlib.figure.Figure at 0x4cbd390>
The same parameters can also be used in the layout manager:

fig, axes = plt.subplots(figsize=(12,3))

axes.plot(x, y,'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');


Save chart

You can use savefig to save the chart

fig.savefig("filename.png")
Here we can also specify the DPI selectively and choose different output formats:

fig.savefig("filename.png", dpi=200)
What formats are there? Which format can get the best quality?

Matplotlib can generate high-quality images in many formats, including PNG, JPG, EPS, SVG, PGF and PDF. If it is a scientific paper, I suggest using pdf format as much as possible. (LaTeX documents compiled by pdflatex can include PDF files using the includegraphics command). In some cases, PGF is also a good choice.

Legend, axis and title
Now that we have introduced how to create a chart canvas and how to add new coordinate axis instances, let's take a look at how to add a title, axis labels and legend

title

Each axis instance can be added with a title, just call the set_title method of the axis instance:

ax.set_title("title");
Axis

Similarly, set_xlabel and set_ylabel can set the x-axis and y-axis labels of the coordinate axis.

ax.set_xlabel("x")
ax.set_ylabel("y");
legend

There are two ways to add a legend to the diagram. One is to call the legend method of the coordinate axis object, passing in a list/tuple of legend text corresponding to the previously defined curves:

ax.legend([“curve1”, “curve2”, “curve3”]);

However, this method is prone to errors, such as adding a new curve or removing a curve. A better way is to use the label=”label text” parameter when calling the plot method, and then call the legend method to add the legend:

ax.plot(x, x**2, label="curve1")
ax.plot(x, x**3, label="curve2")
ax.legend();
legend also has an optional parameter loc to determine the location of the legend, see: http://matplotlib.org/users/legend_guide.html#legend-location

The most commonly used values are as follows:

ax.legend(loc=0) # let matplotlib decide the optimal location
ax.legend(loc=1) # upper right corner
ax.legend(loc=2) # upper left corner
ax.legend(loc=3) # lower left corner
ax.legend(loc=4) # lower right corner
# .. many more options are available

=> <matplotlib.legend.Legend at 0x4c863d0>
The following example also includes the use of titles, axis labels, and legends:

import matplotlib.pyplot as plt
from pylab import *
x = linspace(0, 5, 10)
y = x ** 2

fig, ax = plt.subplots()

ax.plot(x, x**2, label="y = x**2")
ax.plot(x, x**3, label="y = x**3")
ax.legend(loc=2); # upper left corner
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title');

plt.show()


Formatted text, LaTeX, font size, font type

Matplotlib provides good support for LaTeX. We only need to encapsulate the LaTeX expression in the symbol, and it can be displayed in any text in the figure, such as "in the symbol, it can be displayed in any text in the figure, such as"

But here we will encounter some small problems, in LaTeX we often use backslashes, such as \alpha to generate the symbol αα

import matplotlib.pyplot as plt
from pylab import *
x = linspace(0, 5, 10)
y = x ** 2

fig, ax = plt.subplots()

ax.plot(x, x**2, label=r"$y = \alpha^2$")
ax.plot(x, x**3, label=r"$y = \alpha^3$")
ax.legend(loc=2) # upper left corner
ax.set_xlabel(r'$\alpha$', fontsize=18)
ax.set_ylabel(r'$y$', fontsize=18)
ax.set_title('title');


plt.show()


We can change the global font size or type:

from matplotlib import rcParams
rcParams.update({'font.size': 18,'font.family':'serif'})
STIX font is a good choice:

matplotlib.rcParams.update({'font.size': 18,'font.family':'STIXGeneral','mathtext.fontset':'stix'})
We can also render all the text in the picture with Latex:

matplotlib.rcParams.update({'font.size': 18,'text.usetex': True})
Set color, line width and line style

colour

With matplotlib, we have many ways to define the color of lines and many other graphical elements. First, we can use MATLAB-like syntax,'b' for blue,'g' for green, and so on. matplotlib also supports the method used by the MATLAB API to select the line type: for example, ‘b.-’ means the blue line marks the point:

# MATLAB style line color and style
ax.plot(x, x**2,'b.-') # blue line with dots
ax.plot(x, x**3,'g--') # green dashed line


=> [<matplotlib.lines.Line2D at 0x4985810>]
We can also choose a color by its name or RGB value. The alpha parameter determines the transparency of the color.
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.