Draw charts in Python with Matplotlib library – Draw a chart in Python with Matplotlib
Given the popularity of Python as a language for data analysis, this tutorial focuses on charting in Python using a popular Matplotlib library.
In the following, we have a look at the article on how to draw graphs in MATLAB .
Matteplet Lib is a large library, which can be a little tricky for a beginner, even if Python is a relatively comfortable language. While mapping is easy with a few lines of code, it is difficult to understand what is actually going on at the end of the library.
This tutorial explains the basic concepts of Matplotlib so that one can discover its full potential.
Introduction to pyplot
matplotlib.pyplot is a set of commandstyle functions that make Matplotlib work like MATLAB. Each pyplot function makes changes to a shape: for example, it creates a shape, it creates a map area in a shape, it draws some lines on a map, it decorates the design with labels, and so on. he does.
In matplotlib.pyplot different states are retained in the function calls, so that it holds things like the current shape and the mapping area, and the mapping functions are routed to the current axes (please note that “axes” in Here and in most places in the documents it is about the axes of a shape and not the exact mathematical term for more than one axis).
Note
The pyplot APP in Matplotlib is generally more flexible than the objectoriented API. Many of the function calls you see here can also be read as methods of an Axes object. We recommend reviewing these tutorials and examples to see how they work.
Creating visualization with pyplot is very fast:
1
2
3
4
5
6
7

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel(‘some numbers’)
plt.show()

Create linear visualizations with Matplotlib
You may be wondering why the xaxis varies from 03 and the yaxis from 14. If you provide a single list or array to the () command in the () scheme, Matplotlib assumes that it is a sequence of y values, and automatically generates x values for you. Because Python domains start with 0, the x vector has a length of Y by default but starts with 0. Hence the data are x [0,1,2,3].
Plot () is a versatile command and will take any number of arguments. For example, to draw x versus y, you can issue the command:
1

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

Format your design
For each pair of arguments x, y, there is an optional third argument, which is a format string that indicates the color and type of the map line. String letters and symbols are formats from MATLAB, and you combine a string of colors with a linestyle string. The default format string is “b“, which is a solid blue line. For example, to draw the above with red circles in Matplotlib, you export:
1
2
3
4
5

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], ‘ro’)
plt.axis([0, 6, 0, 20])
plt.show()

Point chart with matplotlib
See the design () documentation for a complete list of line styles and template strings. The ax () command in the example above takes a list of [xmin, xmax, ymin, ymax] and specifies the view of the axes.
If Matplotlib was limited to working with lists, it would be completely useless for numerical processing. You will generally use numpy arrays. In fact, all sequences are converted internally to dial arrays. The following example shows how to draw multiple lines with different formatting styles in a command using arrays.
1
2
3
4
5
6
7
8
9
10
11

import numpy as np
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, ‘r–‘, t, t**2, ‘bs’, t, t**3, ‘g^’)
plt.show()

Draw with keyword strings
There are items that provide data in a format that allows you to access specific variables with strings. For example, with numpy.recarray or pandas.DataFrame.
Matplotlib lets you present data keyword arguments to objects. If presented, you may have problems with strings related to these variables.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

data = {‘a’: np.arange(50),
‘c’: np.random.randint(0, 50, 50),
‘d’: np.random.randn(50)}
data[‘b’] = data[‘a’] + 10 * np.random.randn(50)
data[‘d’] = np.abs(data[‘d’]) * 100
plt.scatter(‘a’, ‘b’, c=‘c’, s=‘d’, data=data)
plt.xlabel(‘entry a’)
plt.ylabel(‘entry b’)
plt.show()

Control line properties
Lines have many properties that you can adjust: bandwidth, line style, line color, and more. There are several ways to set line properties.
Use keyword arguments:
1

plt.plot(x, y, linewidth=2.0)

If you use Line2D sample adjustment methods. The map returns a list of Line2D objects. For example, .line1, line2 = plot (x1, y1, x2, y2) In the following code we will assume that we have only one line so that the returned list is of length 1. We use the tuple package with the line to get the first element of that list:
1
2
3

line, = plt.plot(x, y, ‘‘)
line.set_antialiased(False) # turn off antialiasing

Use the setp () command. The following example uses a Matplotlibstyle command to set several properties in the line list. setp works transparently with a list of objects or a single object. You can use Python keyword arguments or MATLAB style string / value pairs:
1
2
3
4
5
6
7
8
9

lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color=‘r’, linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, ‘color’, ‘r’, ‘linewidth’, 2.0)

Work with multiple shapes and axes
MATLAB and pyplot have the meaning of current shape and current axes. All drawing commands apply to current axes. The gca () function returns the current axes (Matplotlib.axes.Axes), and the gcf () function returns the current shape (matplotlib.figure.Figure). Normally, you do not have to worry about this, because all these issues are taken care of behind the scenes. Below is a script to create two subcategories.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

def f(t):
return np.exp(–t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure()
plt.subplot(211)
plt.plot(t1, f(t1), ‘bo’, t2, f(t2), ‘k’)
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), ‘r–‘)
plt.show()

Work with multiple axes in matplotlib
The figure () command in the example above is optional because figure (1) is created by default, exactly as the default (111) is created by default if you do not manually specify any axis. command in the subplot command is optional if numrows * numcols <10. Thus (subplot (211) is the same as (1,1, subplot (2).
In Matplotlib you can create any number of subaxes. If you want to place the axes manually, use the axes () command, which allows you to specify the location as the axes ([left, bottom, width, height]) where all values are They are in the form of fractions. Axes Demo for example of manually placing axes and Basic Subplot Demo for example with many subdirectories.
You can use multiple figures () to create more shapes on the page.
Of course, each shape can contain axes and subcategories, as you see fit in the following code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

import matplotlib.pyplot as plt
plt.figure(1) # the first figure
plt.subplot(211) # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212) # the second subplot in the first figure
plt.plot([4, 5, 6])
plt.figure(2) # a second figure
plt.plot([4, 5, 6]) # creates a subplot(111) by default
plt.figure(1) # figure 1 current; subplot(212) still current
plt.subplot(211) # make subplot(211) in figure1 current
plt.title(‘Easy as 1, 2, 3’) # subplot 211 title

You can clear the current shape with the clf () function and the current axes with cla (). Do not despair if you feel you have a problem because the modes in the Matplotlib library (specifically the current image, shapes and axes) are stored behind the scenes for you, do not despair.
This is just a special case method around an object oriented API that you can use instead. I hope we have provided you with important information about charting in Python with the Matplotlib library.
1 Comments
[…] as soon as they enter the Linux operating system because Linux has no user interface. It is not installed on it by default, today in this post we will discuss the benefits and types of user interfaces that […]