0 代码import的包

1
2
3
4
5
6
from matplotlib import pyplot as plt
from matplotlib.pyplot import savefig
import numpy as np
import pandas as pd
from statsmodels.graphics.tsaplots import plot_acf
import matplotlib.gridspec as gs

1 散点图

1.1 normal scatter

1
2
3
4
5
6
7
8
9
def scatter():
x = np.random.randint(1,20,10)
y = np.random.randint(1,10,10)
plt.scatter(x,y)
plt.xlabel("x values") # 设置x轴的显示
plt.ylabel("y values") # 设置y轴的显示
plt.title("scatter test") #设置标题
savefig("img/scatter.png") #保存图片 该语句必须放在plt.show()之前,否则会是空白
plt.show() #显示

1.2 add a colorbar

1
2
3
4
5
6
7
8
9
10
def scatter():
x = np.random.randint(1,80,40)
y = np.random.randint(1,100,40)
plt.scatter(x,y,c=y,cmap="Spectral") # ket code
plt.colorbar() # key codde
plt.xlabel("x values") # 设置x轴的显示
plt.ylabel("y values") # 设置y轴的显示
plt.title("scatter with colorbar") #设置标题
savefig("img/scatter_colorbar.png") #保存图片 该语句必须放在plt.show()之前,否则会是空白
plt.show() #显示

2 折线图

2.1 draw a function

1
2
3
4
5
6
7
8
def line():
x = np.arange(-5,5,0.02)
plt.plot(x,np.power(x,2))
plt.xlabel("x values") # 设置x轴的显示
plt.ylabel("y values") # 设置y轴的显示
plt.title("line test") # 设置标题
savefig("img/line.png") # 保存图片 该语句必须放在plt.show()之前,否则会是空白
plt.show()

2.2 draw stuck data

1
2
3
4
5
6
7
8
9
10
11
def line():
data = pd.read_csv("data/000001.SZ.csv")
x = pd.to_datetime([str(i) for i in data["trade_date"].values])
y = data["close"]
plt.figure(figsize=(16,12))
plt.plot(x,y)
plt.xlabel("year") # 设置x轴的显示
plt.ylabel("close data") # 设置y轴的显示
plt.title("stuck data chart") # 设置标题
savefig("img/line-stuck.png") # 保存图片 该语句必须放在plt.show()之前,否则会是空白
plt.show()

2.3 marker

1
2
3
4
5
6
7
8
'''
marker, 指定标签,相关标签样式见下表
markevery, 指定间隔多少个值画一个标签
'''
plt.plot([i for i in range(1,30)], marker="x", markevery=2)
plt.plot([i for i in range(3,32)], marker="o", markevery=2)
plt.legend(loc="best")
plt.show()
marker symbol description
"." m00 point
"," m01 pixel
"o" m02 circle
"v" m03 triangle_down
"^" m04 triangle_up
"<" m05 triangle_left
">" m06 triangle_right
"1" m07 tri_down
"2" m08 tri_up
"3" m09 tri_left
"4" m10 tri_right
"8" m11 octagon
"s" m12 square
"p" m13 pentagon
"P" m23 plus (filled)
"*" m14 star
"h" m15 hexagon1
"H" m16 hexagon2
"+" m17 plus
"x" m18 x
"X" m24 x (filled)
"D" m19 diamond
"d" m20 thin_diamond
`” “` m21
"_" m22 hline

3 柱状图

3.1 simple bar chart

1
2
3
4
5
6
7
8
9
def bar():
x = [1,2,3,4,5]
y = [15,8,10,17,12]
plt.bar(x,y)
plt.xlabel("x values") # 设置x轴的显示
plt.ylabel("y values") # 设置y轴的显示
plt.title("bar test") # 设置标题
savefig("img/bar.png") # 保存图片 该语句必须放在plt.show()之前,否则会是空白
plt.show()

3.2 add color

1
2
3
4
5
6
7
8
9
def bar():
x = [1,2,3,4,5]
y = [15,8,10,17,12]
plt.bar(x,y,color="rgb")
plt.xlabel("x values") # 设置x轴的显示
plt.ylabel("y values") # 设置y轴的显示
plt.title("bar test") # 设置标题
savefig("img/bar.png") # 保存图片 该语句必须放在plt.show()之前,否则会是空白
plt.show()

3.3 add target

1
2
3
4
5
6
7
8
9
def bar():
x = [1,2,3,4,5]
y = [15,8,10,17,12]
plt.bar(x,y,color="rgb",tick_label=["mon","thu","wen","tu","fri"])
plt.xlabel("x values") # 设置x轴的显示
plt.ylabel("y values") # 设置y轴的显示
plt.title("bar test") # 设置标题
savefig("img/bar_target.png") # 保存图片 该语句必须放在plt.show()之前,否则会是空白
plt.show()

3.4 stack bar

1
2
3
4
5
6
7
8
9
10
11
12
def bar():
x = [1,2,3,4,5]
y = [15,8,10,17,12]
y2 = [3,2,5,4,3]
plt.bar(x,y,color="red",label="money")
plt.bar(x,y2,color="b",bottom=y,label="cash",tick_label=["mon","thu","wen","tu","fri"])
plt.legend(loc="best")
plt.xlabel("x values") # 设置x轴的显示
plt.ylabel("y values") # 设置y轴的显示
plt.title("bar test") # 设置标题
savefig("img/bar_stack.png") # 保存图片 该语句必须放在plt.show()之前,否则会是空白
plt.show()

3.5 paralleling bar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def bar():
x = [1,2,3,4,5]
y = [15,8,10,17,12]
y2 = [3,2,5,4,3]
width = 0.4
plt.bar(x,y,color="red",label="money",width=width)
for i in range(len(x)):
x[i] += width #增加X轴的距离
plt.bar(x,y2,color="b", width=width, label="cash",tick_label=["mon","thu","wen","tu","fri"])
plt.legend(loc="best")
plt.xlabel("x values") # 设置x轴的显示
plt.ylabel("y values") # 设置y轴的显示
plt.title("bar test") # 设置标题
savefig("img/bar_paralleling.png") # 保存图片 该语句必须放在plt.show()之前,否则会是空白
plt.show()

3.6 bar-type bar chart

1
2
3
4
5
6
7
8
9
10
11
12
def bar():
x = [1,2,3,4,5]
y = [15,8,10,17,12]
y2 = [3,2,5,4,3]
height = 0.9
plt.barh(x,y,color="red",label="money",height=height,tick_label=["mon","thu","wen","tu","fri"])
plt.legend(loc="best")
plt.xlabel("y values") # 设置x轴的显示
plt.ylabel("x values") # 设置y轴的显示
plt.title("bar test") # 设置标题
savefig("img/bar_type.png") # 保存图片 该语句必须放在plt.show()之前,否则会是空白
plt.show()

4 饼图

4.1 normal

1
2
3
4
5
6
7
8
9
def pie():
x = ["mon","thu","wen","tu","fri"]
y = [190,180,200,222,230]
color = ["cyan","green","red","pink","yellow"]
plt.pie(y,labels=x,colors=color,shadow=True,autopct="%1.2f%%")
plt.legend(loc="best")
plt.title("pie chart")
savefig("img/pie.png")
plt.show()

4.2 exploded

1
2
3
4
5
6
7
8
9
10
11
12
import matplotlib

matplotlib.rcParams['font.family'] = 'Simsun'
matplotlib.rcParams['font.size'] = 20
x = [u"交通事故", u"水灾事故", u"其他事故"]
y = [4005, 3625, 1206]
color = ["cyan", "green", "red", "pink", "yellow", "b"]
exploed = (0, 0.1, 0) ## 关键代码
plt.pie(y, labels=x, colors=color, shadow=True, autopct="%1.2f%%", explode=exploed)
plt.tight_layout()
plt.savefig("img/pie2.png")
plt.show()

5 子图

5.1 subplot

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
28
29
30
31
32
33
34
35
36
def subpl():
plt.figure(1)
# sub 1
plt.subplot(221)# 将画面分成2行2列共4个plot,下面的数据显示在第一个plot中
data = pd.read_csv("data/000001.SZ.csv")
x = pd.to_datetime([str(i) for i in data["trade_date"].values])
y = data["close"]
plt.plot(x, y)
plt.xlabel("year") # 设置x轴的显示
plt.ylabel("close data") # 设置y轴的显示
plt.title("stuck data chart") # 设置标题
# sub 2
plot_acf(y.diff().dropna(),ax=plt.subplot(222))
# sub 3
plt.subplot(223)
x = [1, 2, 3, 4, 5]
y = [15, 8, 10, 17, 12]
y2 = [3, 2, 5, 4, 3]
height = 0.4
labels = ["mon", "thu", "wen", "tu", "fri"]
plt.bar(x, y, color="red", label="money", width=height, tick_label=labels)
for i in range(len(x)):
x[i] += height
plt.bar(x,y2,width=height,color="pink",label="cash")
plt.legend(loc="best")
plt.xlabel("y values") # 设置x轴的显示
plt.ylabel("x values") # 设置y轴的显示
plt.title("bar test") # 设置标题
# sub 4
plt.subplot(224)
y = [190, 180, 200, 222, 230]
color = ["cyan", "green", "red", "pink", "yellow"]
plt.pie(y, labels=labels, colors=color, shadow=True, autopct="%1.2f%%")
plt.title("pie chart")
savefig("img/subplot.png")
plt.show()

5.2 subplots

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
28
29
30
31
32
33
34
35
def subplots():
# subplots显示subplot的数据
fig, ax = plt.subplots(2,2) # 画2行2列共4个plot,返回的是一个元组型的数据,fig是画布,ax是子图
data = pd.read_csv("data/000001.SZ.csv")
x = pd.to_datetime([str(i) for i in data["trade_date"].values])
y = data["close"]
# sub 1
ax[0][0].plot(x, y)
ax[0,0].set_xlabel("year")
ax[0,0].set_ylabel("close")
ax[0,0].set_title("stuck data")
# sub 2
plot_acf(y.diff().dropna(),ax=ax[0,1])
ax[0,1].set_title("one diff")
# sub 3
x = [1, 2, 3, 4, 5]
y = [15, 8, 10, 17, 12]
y2 = [3, 2, 5, 4, 3]
height = 0.4
labels = ["mon", "thu", "wen", "tu", "fri"]
ax[1,0].bar(x, y, color="red", label="money", width=height, tick_label=labels)
for i in range(len(x)):
x[i] += height
ax[1,0].bar(x, y2, width=height, color="pink", label="cash")
ax[1,0].legend(loc="best")
ax[1,0].set_xlabel("y values") # 设置x轴的显示
ax[1,0].set_ylabel("x values") # 设置y轴的显示
ax[1,0].set_title("bar test") # 设置标题
# sub 4
y = [190, 180, 200, 222, 230]
color = ["cyan", "green", "red", "pink", "yellow"]
ax[1,1].pie(y, labels=labels, colors=color, shadow=True, autopct="%1.2f%%")
ax[1,1].set_title("pie chart")
savefig("img/subplots.png")
plt.show()

5.3 subplot2gird

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
28
29
30
31
32
33
def subgrid():
shape = (3,3)
ax1 = plt.subplot2grid(shape,(0,0),rowspan=1,colspan=3)
data = pd.read_csv("data/000001.SZ.csv")
year = pd.to_datetime([str(i) for i in data["trade_date"].values])
clo = data["close"]
# sub 1
ax1.plot(year,clo)
ax1.set_xlabel("year")
ax1.set_ylabel("close")
ax1.set_title("stuck data")
# sub 2
ax2 = plt.subplot2grid(shape,(1,0),rowspan=1,colspan=2)
plot_acf(clo.diff().dropna(),ax=ax2)
ax2.set_title("one diff")
# sub 3
ax3 = plt.subplot2grid(shape,(1,2))
x = [1, 2, 3, 4, 5]
y = [15, 8, 10, 17, 12]
height = 0.4
labels = ["mon", "thu", "wen", "tu", "fri"]
ax3.bar(x, y, color="red", label="money", width=height, tick_label=labels)
ax3.set_title("bar chart")
ax3.set_xlabel("week")
ax3.set_ylabel("money")
#sub 4
ax4 = plt.subplot2grid(shape,(2,0),rowspan=1,colspan=3)
ax4.plot(year,clo.diff())
ax4.set_title("one diff")
ax4.set_xlabel("year")
ax4.set_ylabel("close")
savefig("img/subplot2grid.png")
plt.show()

5.4 gridspec

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
28
29
30
31
32
33
34
def gridspec():
plt.figure(1)
g = gs.GridSpec(3,3) # 定义3行3列
ax1 = plt.subplot(g[0,:]) # 使用索引进行标记位置,第一个0表示第一行,第二个:号,表示所有列
data = pd.read_csv("data/000001.SZ.csv")
year = pd.to_datetime([str(i) for i in data["trade_date"].values])
clo = data["close"]
# sub 1
ax1.plot(year, clo)
ax1.set_xlabel("year")
ax1.set_ylabel("close")
ax1.set_title("stuck data")
# sub 2
ax2 = plt.subplot(g[1,0])
x = [1, 2, 3, 4, 5]
y = [15, 8, 10, 17, 12]
height = 0.4
labels = ["mon", "thu", "wen", "tu", "fri"]
ax2.bar(x, y, color="red", label="money", width=height, tick_label=labels)
ax2.set_title("bar chart")
ax2.set_xlabel("week")
ax2.set_ylabel("money")
# sub 3
ax3 = plt.subplot(g[1,1:])
plot_acf(clo.diff().dropna(), ax=ax3)
ax3.set_title("one diff")
# sub 4
ax4 = plt.subplot(g[2,:])
ax4.plot(year, clo.diff())
ax4.set_title("one diff")
ax4.set_xlabel("year")
ax4.set_ylabel("close")
savefig("img/gridspec.png")
plt.show()

写在最后

欢迎大家关注鄙人的公众号【麦田里的守望者zhg】,让我们一起成长,谢谢。
微信公众号