Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money. @TOC

preface

All drawings provided by Matplotlib come with default styles. While this allows for quick drawing, sometimes you may need to customize the color and style of your drawing to produce a more elegant, aesthetically pleasing image. Matplotlib is designed with this requirement in mind, making it easy to style matplotlib graphics.

Control fill style

Matplotlib provides a fill pattern for filling a plane. These fill patterns are important for graphics that contain only black and white.

import numpy as np
import matplotlib.pyplot as plt
n = 10
a = np.random.random(n)
b = np.random.random(n)
x = np.arange(n)
plt.bar(x, a, color='w', hatch='x', edgecolor='black')
plt.bar(x, a+b, bottom=a, color='w', edgecolor='black', hatch='/')
plt.show()
Copy the code

With filling present sexual function (such as pyplot bar ()) accept optional parameters hatch control filling style, optional values of these parameters include: "/", "\", "|", "-", "+", "x", "o", "o", "" and" * ", each value corresponding to the different filling pattern; The Edgecolor parameter can be used to control the color of the pattern fill.

Control tag style

In detail on the Drawing of Common Statistical Graphs, we have seen how to draw curves and that curves are made up of lines between points. In addition, a scatter plot represents each point in the data set. Matplotlib, on the other hand, provides a variety of shapes that can replace the style of points with other types of tags. Tags can be specified in the following ways:

  1. Predefined tags: Predefined shapes, represented as integers in the range [0, 8] or some predefined string.
  2. Vertex list: A list of value pairs used as coordinates for the shape path.
  3. Regular polygon: Triplet representing n-sided regular polygons (N, 0, Angle), where Angle is the rotation Angle.
  4. Star polygon: This is represented as a triplet (N, 1, Angle), representing n-sided positive stars, where Angle is the rotation Angle.
import numpy as np
import matplotlib.pyplot as plt
a = np.random.standard_normal((100.2))
a += np.array((-1, -1))
b = np.random.standard_normal((100.2))
b += np.array((1.1))
plt.scatter(a[:,0], a[:,1], color = 'm', marker = 'x')
plt.scatter(b[:,0], b[:,1], color = 'c', marker = A '^')
plt.show()
Copy the code

Using the marker parameter, you can specify different markers for each collection of data sets.

We’ve learned how to define a different color for each point in a scatter plot, what if we need to define a different style for each point? The problem is that, unlike the color parameter, the marker parameter does not accept a list of marked styles as input. Therefore, we cannot implement a single call of PLt.Scatter () to show multiple point sets with different markings. The solution is to separate each type of data points into different sets and call Pyplot.Scatter () separately for each set:

import numpy as np
import matplotlib.pyplot as plt
label_list = (
    b'Iris-setosa'.b'Iris-versicolor'.b'Iris-virginica',
)
colors = ['c'.'y'.'m']
def read_label(label) :
    return label_list.index(label)
data = np.loadtxt('iris.data', delimiter = ', ', converters = { 4 : read_label })
marker_set = (A '^'.'x'.'. ')
for i, marker in enumerate(marker_set):
    data_subset = np.asarray([x for x in data if x[4] == i])
    plt.scatter(data_subset[:,0], data_subset[:,1], color = colors[i], marker = marker)
plt.show()
Copy the code

For Pyplot.plot (), the tag style can also be accessed using the same tag parameter. When data points are dense, displaying each point with a marker will result in a cluttered image, so matplotlib provides the markevery parameter to allow displaying a marker every N points:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-6.6.1024)
y_1 = np.sinc(x)
y_2 = np.sinc(x) + 1
plt.plot(x, y_1, marker = 'x', color = '75')
plt.plot(x, y_2, marker = 'o', color = 'k', markevery = 64)
plt.show()
Copy the code

Control tag size

The size of the mark can be controlled by the optional parameter S:

import numpy as np
import matplotlib.pyplot as plt
a = np.random.standard_normal((100.2))
a += np.array((-1, -1))
b = np.random.standard_normal((100.2))
b += np.array((1.1))
plt.scatter(a[:,0], a[:,1], c = 'm', s = 100.)
plt.scatter(b[:,0], b[:,1], c = 'c', s = 25.)
plt.show()
Copy the code

Tips: The size of the markers is set by the parameter S of plt.scatter(), but note that it sets the surface area multiplier of the markers rather than the radius. The plt.scatter() function also accepts lists as input to the s parameter, which represents a size for each point:

import numpy as np
import matplotlib.pyplot as plt
m = np.random.standard_normal((1000.2))
r_list = np.sum(m ** 2, axis = 1)
plt.scatter(m[:, 0], m[:, 1], c = 'w', edgecolor='c', marker = 'o', s = 32. * r_list)
plt.show()
Copy the code

The Tips: plt.plot() function allows you to change the size of the tag with the help of the markersize(or ms for short) parameter, but this parameter does not accept a list as input.

Create custom tags

Although Matplotlib provides a variety of tag shapes. But in some cases we may still not be able to find the right shape for our specific needs. For example, we might want to use something like a corporate logo as a shape. In Matplotlib, a shape is described as a path — a series of points connected. Therefore, to define our own tag shape, we must provide a series of points:

import numpy as np
import matplotlib.path as mpath
from matplotlib import pyplot as plt
shape_description = [
    ( 1..2., mpath.Path.MOVETO),
    ( 1..1., mpath.Path.LINETO),
    ( 2..1., mpath.Path.LINETO),
    ( 2., -1., mpath.Path.LINETO),
    ( 1., -1., mpath.Path.LINETO),
    ( 1., -2., mpath.Path.LINETO),
    (-1., -2., mpath.Path.LINETO),
    (-1., -1., mpath.Path.LINETO),
    (-2., -1., mpath.Path.LINETO),
    (-2..1., mpath.Path.LINETO),
    (-1..1., mpath.Path.LINETO),
    (-1..2., mpath.Path.LINETO),
    ( 0..0., mpath.Path.CLOSEPOLY),
]
u, v, codes = zip(*shape_description)
my_marker = mpath.Path(np.asarray((u, v)).T, codes)
data = np.random.rand(8.8)
plt.scatter(data[:,0], data[:, 1], c = 'm', marker = my_marker, s = 75)
plt.show()
Copy the code

Tips: All Pyplot functions with tagged graphs have an optional parameter marker, whose parameter value can be a predefined Matplotlib marker or a custom instance of a path object defined in the matplotlib.path module.

The constructor of the Path object takes a list of coordinates and an instruction list as input; One instruction per coordinate, fuses the coordinates and instructions together with a list, and passes the list of coordinates and instructions to the path constructor as follows:

u, v, codes = zip(*shape_description)
my_marker = mpath.Path(np.asarray((u, v)).T, codes)
Copy the code

Shapes are described by the movement of the cursor:

  • MOVETO: This instruction moves the cursor to the specified coordinates without drawing a line.
  • LINETO: This draws a line between the current point of the cursor and the target point, and moves the cursor to the target point.
  • CLOSEPOLY: This instruction is used only to close the path, and each shape ends with this instruction.

In theory, any shape is possible, we just need to describe its path. In practice, if you want to use complex shapes, it is best to do the conversion work in advance.

Series of links

Matplotlib common statistical graph drawing

Matplotlib uses custom colors to draw statistics

Matplotlib controls line style and line width