Matplotlib for Python data visualization

Time:2020-10-14

1、 Common module import

import numpy as np
import matplotlib
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from mpl_toolkits.mplot3d import Axes3D

2、 Solve the problem of abnormal display

Chinese random code

myfont =  fm.FontProperties (fname = font file path)

The negative sign is shown as a square

matplotlib.rcParams['axes.unicode_minus']=False

3、 Line chart

Generating data

x =  np.linspace - np.pi , np.pi , 256, endpoint = true) ා take 256 points equidistant from - π to π
Y_ cos, y_ sin =  np.cos (x),  np.sin (x) COS and sin values of X corresponding to ා

Initialize canvas

plt.figure (figsize = (8,6), DPI = 80) # figsize defines the canvas size, and DPI defines the canvas resolution
plt.title ("simple line chart", fontproperties = myfont) ා set the title, Chinese needs to specify the font
plt.grid (true) ා show grid

Set axis

#Set X axis
plt.xlabel ("X-axis", fontproperties = myfont) ා axis label
plt.xlim (- 4.0, 4.0) × axis range
plt.xticks ( np.linspace (- 4, 4, 9, endpoint = true)) # axis scale

#Set Y axis
plt.ylabel ("Y-axis", fontproperties = myfont)
plt.ylim(-1.0, 1.0)
plt.yticks(np.linspace(-1, 1, 9, endpoint=True))

Drawing data

There are several types of lines: “G + -“, “R * -“, “B. -“, and “yo -“. The first character represents the color, the second character represents the node style, and the third character represents the line style

plt.plot (x, y_ COS, "B --", linewidth = 2.0, label = cos example ") ා the first two parameters are coordinate values, the third parameter is line type, linewidth is line width, and label is legend text
plt.plot (x, y_ Sin, "G -", linewidth = 2.0, label = sin example ")

Set legend

plt.legend (LOC = upper left ", prop = myfont, shadow = true) # LOC can be a combination of upper, lower and left, right, center

graphic display

plt.show()

Matplotlib for Python data visualization

Area map

plt.fill_between(x, -1, y_sin, where=True, color="blue", alpha=0.25)
plt.show()

Matplotlib for Python data visualization

3-D line chart

#Generate test data
x = np.linspace(0, 1, 1000)
y = np.linspace(0, 1, 1000)
z = np.sin(x * 2 * np.pi) / (y + 0.1)

#Generate canvas (two forms)
fig = plt.figure()
ax = fig.gca(projection="3d",)
# ax = fig.add_subplot(111, projection="3d",)

#Draw 3-D line chart
ax.plot(x, y, z, color="red", linestyle="-")

#Set axis Icon
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_zlabel("Z Label")

#Graphic display
plt.show()

Matplotlib for Python data visualization

4、 Bar chart

Generating data

#Generate test data
means_men = np.array((20, 35, 30, 35, 27))
means_women = np.array((25, 32, 34, 20, 25))

Initialize canvas

plt.figure (figsize = (8,6), DPI = 80) # figsize defines the canvas size, and DPI defines the canvas resolution
plt.title ("simple histogram", fontproperties = myfont) ා set the title, and Chinese needs to specify the font
plt.grid (true) ා show grid

Set axis

index = np.arange(len(means_men)) [0,1,2,3,4]
bar_ Height = 0.35 ᦇ column width
plt.xlim (0, 45) ා axis range
plt.xlabel ("scores") axis label
plt.ylabel("Group")
plt.yticks (index + (bar_ Height / 2), ("a", "B", "C", "d", "e")) # axis scale

Drawing data

#Draw a horizontal bar chart
plt.barh(index, means_men, height=bar_height, alpha=0.2, color="b", label="Men")
plt.barh(index + bar_height, means_women, height=bar_height, alpha=0.8, color="r", label="Women")

Set legend

plt.legend(loc="upper right", shadow=True)

Display data values

for i, v in zip(index, means_men):
    plt.text(v + 0.3, i, v, ha="left", va="center")
for i, v in zip(index, means_women):
    plt.text(v + 0.3, i + bar_height, v, ha="left", va="center")

graphic display

plt.show()

Matplotlib for Python data visualization

Vertical column chart

Set the axis, X and Y swap

index = np.arange(len(means_men)) [0,1,2,3,4]
bar_ Height = 0.35 ᦇ column width
plt.ylim(0, 45)
plt.ylabel("Scores")
plt.xlabel("Group")
plt.xticks(index + (bar_height / 2), ("A", "B", "C", "D", "E"))

Drawing data

#Draw vertical bar chart
plt.bar(index-bar_height/2, means_men, width=bar_height, alpha=0.4, color="b", label="Men")
plt.bar(index+bar_height/2, means_women, width=bar_height, alpha=0.4, color="r", label="Women")

graphic display

plt.show()

Matplotlib for Python data visualization

stacked column chart

#Generate test data
data = np.array([
    [1, 4, 2, 5, 2],
    [2, 1, 1, 3, 6],
    [5, 3, 6, 4, 1]
])

#Set title
plt.title ("hierarchical histogram", fontproperties = myfont)

#Set related parameters
index = np.arange(len(data[0]))
color_index = ["r", "g", "b"]

#Declaration bottom position
bottom = np.array([0, 0, 0, 0, 0])

#Draw in turn and update the bottom position
for i in range(len(data)):
    plt.bar (index, data[i], width=0.5, color=color_ Index [i], bottom = bottom, alpha = 0.7, label = label% d "% I)
    bottom += data[i]

#Set legend location
plt.legend(loc="upper left", prop=myfont, shadow=True)

#Graphic display
plt.show()

Matplotlib for Python data visualization

histogram

#Generate test data
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

#Set title
plt.title ("histogram", fontproperties = myfont)

#Draw a histogram and return the relevant results
n, bins, patches =  plt.hist (x, bins = 50, density = 1, cumulative = false, color = green, alpha = 0.6, label = histogram)

## draw a line chart according to the results returned from the histogram
y = mlab.normpdf(bins, mu, sigma)
plt.plot (bins, y, "R --", label = line)

#Set legend location
plt.legend(loc="upper left", prop=myfont, shadow=True)

#Graphic display
plt.show()

Matplotlib for Python data visualization

3-D column chart

#Generate test data (location data)
xpos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ypos = [2, 3, 4, 5, 1, 6, 2, 1, 7, 2]
zpos = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

#Generate test data (cylindrical parameters)
dx = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
dy = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
dz = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#Generate canvas (two forms)
fig = plt.figure()
ax = fig.gca(projection="3d",)

#Set axis Icon
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_zlabel("Z Label")

#Draw a three-dimensional histogram
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, alpha=0.5)

#Graphic display
plt.show()

Matplotlib for Python data visualization

5、 Pie chart

Generating data

#Generate test data
Sizes = [15, 30, 45, 10] ා value
Labels = ["frogs", "Chinese", "dogs", "logs"] #
Colors = ["yellowgreen", "gold", "lightskyblue", "lightcore"] #

Initialize canvas

plt.figure (figsize = (8,6), DPI = 80) # figsize defines the canvas size, and DPI defines the canvas resolution
plt.title ("simple pie chart", fontproperties = myfont) ා set the title, and Chinese needs to specify the font

Set sector offset value

explode = [0, 0.05, 0, 0]

Drawing data

patches, l_ text, p_ text =  plt.pie (sizes, expand = expand, labels = labels, colors = colors, autopct =% 1.1f%% ", shadow = true, startangle = 90) # autopct sets the format of display percentage, and startangle sets the image rotation direction
for text in l_text:
    text.set_ Fontproperties (myfont) ා set font to avoid Chinese garbled code

graphic display

plt.show()

Matplotlib for Python data visualization

6、 Scatter plot

Generating data

N = 1000
x = np.random.randn(N)
y = x + np.random.randn(N)*0.5

Initialize canvas

plt.figure (figsize = (8,6), DPI = 80) # figsize defines the canvas size, and DPI defines the canvas resolution
plt.title ("simple scatter chart", fontproperties = myfont) ා set the title, and Chinese needs to specify the font

Drawing data

plt.scatter (x, y, s = 5, C = red ", marker:" O ") ා s is the size of the point, C is the color of the point, and marker is the shape of the point

graphic display

plt.show()

Matplotlib for Python data visualization

3-D scatter plot

#Generate test data
x = np.random.random(100)
y = np.random.random(100)
z = np.random.random(100)
color = np.random.random(100)
scale = np.random.random(100) * 100

#Generate canvas (two forms)
fig = plt.figure()
fig.suptitle ("3-D scatter plot", fontproperties = myfont)
ax = fig.add_subplot(111, projection="3d")

#Set axis Icon
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_zlabel("Z Label")

#Set axis range
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)

#Draw 3-D scatter plot
ax.scatter(x, y, z, s=scale, c=color, marker=".")

#Graphic display
plt.show()

Matplotlib for Python data visualization

7、 Radar chart

Generating data

labels =  np.array (["group a", "group B", "group C", "group D", "Group E", "Group F"])
data = np.array([68, 83, 90, 77, 89, 73])
theta =  np.linspace (0, 2 *  np.pi , len (data), endpoint = false) # the angle value of each dimension

Initialize canvas

plt.subplot (111, polar = true) ා 3 numbers, the first two digits indicate the canvas is divided into several lines and columns, and the last two digits indicate where the flowers are placed
plt.title ("radar chart", fontproperties = myfont)

Set axis

plt.ylim (0, 100) ා axis range

Drawing data

plt.thetagrids(theta * (180 / np.pi), labels=labels, fontproperties=myfont)

graphic display

plt.show()

Matplotlib for Python data visualization

If you want to know more about programming and development, and grow with me, please pay attention to my official account, “pine nut warehouse”, and share the resources of the house and programmers. Thank you!!!

Recommended Today

Singleton design pattern

Singleton: a class can have only one instance object; How to implement singleton?1) Hungry man style: no matter whether the user needs the object or not, the object is created first; //① Enumeration public class SingletonPattern1 { public static void main(String[] args) { SingleEnum singleEnum1 = SingleEnum.INSTANCE; SingleEnum singleEnum2 = SingleEnum.INSTANCE; System.out.println(singleEnum1==singleEnum2);//true } } enum […]