Data visualization using Matplotlib

Time:2020-6-29

Matplotlib is a drawing library in Python. It inherits the advantages and syntax of MATLIB (it can be seen from its name), so it is very friendly to users who are familiar with MATLIB.

Pylab and pyplot

About pylab and pyplot, people have done a lot of discussion. What are the differences between the two modules? The pylab module is installed with Matplotlib, and pyplot is the internal module of Matplotlib. The two import methods are different, you can choose one to import.

from pylab import *
#Or
import matplotlib.pyplot as plt
import numpy as np

Pylab integrates the functions of pyplot and numpy in the same namespace, so there is no need to import numpy separately. Furthermore, after importing pylab, the functions of pyplot and numpy can be called directly without specifying the module (namespace) to which they belong, so that the development environment of Matplotlib is more like MATLAB.

plot(x,y)
array([1,2,3,4])
#Instead of specifying the module name
plt.plot()
np.array([1,2,3,4])

In most cases, we prefer to use the pyplot module.

Line chart

Here I use jupyter to demonstrate

ipython qtconsole --matplotlib inline

Using Matplotlib to generate this diagram is very simple and can be done in one line of code

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

1.png

As shown, a line2d object is generated. The object is a straight line, which represents the linear extension trend of each data point in the chart. We can see that the data in the list is directly displayed as the value of the y-axis, and the x-week starts from 0, so we need to see a broken line chart of data, just input a list.

However, we can see that this picture may be very simple. For example, there are several problems as follows:

  • The y-axis shows why 0.5 is the step interval, I want to use 1 as the step interval
  • I want to control the value displayed on the x-axis instead of starting at 0
  • The picture is too small. Can you control the size
  • The x-axis and y-axis characters are too small. Can you control the size
  • Name the X and Y axes
  • You can’t see clearly without the grid
  • No legend
  • Dot the line
  • I want to save the pictures locally
  • How to draw a subgraph

Next, we will solve it one by one.

1. Set the step interval of x-axis and y-axis

There are two parameters to control the value displayed on x-axis and y-axis

  • xticks(ticks, [labels], **kwargs)

  • yticks(ticks, [labels], **kwargs)

    • Ticks: control the position of the display, that is, to display the values. These values must be within the range of y value data, which is the range of [1,4].
    • [labels]: control the value displayed in the corresponding position, which can be a number or a character.
y = [1,2,3,4]
step = 1
plt.yticks([i for i in y if i%step == 0]) 
plt.plot(y)

2.png

2. The value displayed on the x-axis

This shows how the axis displays the characters.

Notice the fifth line, I changed it to [1,2,3,3.5,4], so there is an extra 3.5.

y = [1,2,3,4]
scale_ls = range(4)
index_ Ls = ["prosperity", "democracy", "civilization", "harmony"]
plt.xticks(scale_ls,index_ls)
plt.yticks([1,2,3,3.5,4])
plt.plot(y)

Snipaste_2018-10-10_13-17-55.png

3. Control chart size

Several methods to control the size of chart

  • Rcparams: this parameter is used to set some configuration parameters, such as the size and DPI
    • figure.figsize : control the size. The parameter is a binary (x, y), that is, length and width
    • figure.dpi : control DPI
plt.rcParams['figure.figsize'] = (10,5)
plt.rcParams['figure.dpi'] = 200
y = [1,2,3,4]
scale_ls = range(4)
index_ Ls = ["prosperity", "democracy", "civilization", "harmony"]
plt.xticks(scale_ls,index_ls)
plt.yticks([1,2,3,3.5,4])
plt.plot(y)

It’s bigger and clearer here

3.png

4. Adjust the font size of x-axis and y-axis

It is also used to control font sizexticksandyticksIt’s just that it’s usedfontsizeParameter.

plt.rcParams['figure.figsize'] = (10,5)
plt.rcParams['figure.dpi'] = 200
y = [1,2,3,4]
scale_ls = range(4)
index_ Ls = ["prosperity", "democracy", "civilization", "harmony"]
plt.xticks(scale_ls,index_ls,fontsize=20)
plt.yticks([1,2,3,3.5,4],fontsize=20)
plt.plot(y)

Snipaste_2018-10-10_13-46-03.png

5. Name the X and Y axes

use

  • xlabel(str,fontsize=int )
  • ylabel(str,fontsize=int )
plt.rcParams['figure.figsize'] = (10,5)
plt.rcParams['figure.dpi'] = 200
y = [1,2,3,4]
scale_ls = range(4)
index_ Ls = ["prosperity", "democracy", "civilization", "harmony"]
plt.xticks(scale_ls,index_ls,fontsize=20)
plt.yticks([1,2,3,3.5,4],fontsize=20)
plt.xlabel ("core values", fontsize = 20)
plt.ylabel (order, fontsize = 20)
plt.plot(y)

Snipaste_2018-10-10_13-50-42.png

6. Add grid

  • plt.grid (true), plus both horizontal and vertical grids.
  • plt.grid (true, axis = “X”), plus the x-axis grid.
plt.rcParams['figure.figsize'] = (10,5)
plt.rcParams['figure.dpi'] = 200
y = [1,2,3,4]
scale_ls = range(4)
index_ Ls = ["prosperity", "democracy", "civilization", "harmony"]
plt.xticks(scale_ls,index_ls,fontsize=20)
plt.yticks([1,2,3,3.5,4],fontsize=20)
plt.xlabel ("core values", fontsize = 20)
plt.ylabel (order, fontsize = 20)
plt.grid(True,axis="both")
plt.plot(y)

Snipaste_2018-10-10_14-01-54.png

7. Add legend

uselegendMethod. There are several parameters in it

  • Handles: represents the objects that use the curves
  • Labels: represents the corresponding legend text
  • LOC: place
  • Prop: additional parameters, such as size, control the legend size
t = np.arange(0, 2.5, 0.01)
y1 = map(math.sin, math.pi*t)
y2 = map(math.cos, math.pi*t)
l1, = plt.plot(list(y1))
l2, = plt.plot(list(y2))
plt.legend(handles = [l1, l2], labels = ['Sin', 'Cos'], loc = 'best', prop={'size': 20})

Snipaste_2018-10-10_14-13-29.png

8. Line icon point

Only forplotAdd parametersmarkerthat will do

t = np.arange(0, 2.5, 0.1)
y1 = map(math.sin, math.pi*t)
y2 = map(math.cos, math.pi*t)
l1, = plt.plot(list(y1), marker = "o")
l2, = plt.plot(list(y2), marker = "*")
plt.legend(handles = [l1, l2], labels = ['Sin', 'Cos'], loc = 'best', prop={'size': 20})

Snipaste_2018-10-10_14-19-11.png

9. Save pictures to local

For final use onlysavefigmethod

plt.savefig('test.png',dpi=400)

10. Draw subgraphs

It’s used heresubplotmethod

It has three parameters, which are

  • A few lines
  • Several columns
  • How many

Take a chestnut

  1. subplot(2,2,1)2 rows and 2 columns (i.e. the subgraph is arranged in the shape of a field) and the first
  2. subplot(2,1,2)2 rows and 1 column (i.e. the subgraph is arranged in two vertical graph shapes) and the second
t = np.arange(0, 2.5, 0.1)
y1 = map(math.sin, math.pi*t)
y2 = map(math.cos, math.pi*t)

plt.subplot(2, 1, 1)
plt.title("Sin", fontsize=20)
l1, = plt.plot(list(y1), marker = "o")

plt.subplot(2, 1, 2)
plt.title("Cos", fontsize=20)
l2, = plt.plot(list(y2), marker = "*")

I also use it heretitleMethod, add the title to the corresponding chart.

Snipaste_2018-10-10_14-27-58.png