Python数据可视化-Matplotlib
上一篇文章大概介绍了数据可视化-Matplotlib之基础知识。这篇文章我们学习一下常用图形的绘制方法。
常用平面图形
普通图
常用函数可以直接用 plt.plot()* 对象。如:
x = np.linspace(-10,10,100)
y = 1/(1+np.exp(-x)) # sigmoid 函数
z = np.sin(x)
plt.figure(figsize=(10,5))
plt.plot(x,y-0.5,label="$\sigma (x)$",color="r",linewidth=2)
plt.plot(x,z,label="sin(x)",color="b",linewidth=2.5)
plt.title("Matplotlib Figure: koding") #图表标题
plt.legend() #显示图形标签
plt.grid() #显示网格
plt.show() #显示绘图窗口
结果:
条形图
条形图可以利用 plt.bar() (axis.bar())对象,默认是垂直条形。水平条形图可以利用 plt.barh()
语法:plt.bar(x, height, width, bottom=None, *, align=‘center’, data=None, **kwargs)
参数说明:
x : 每个条形的 X 坐标标签(向量)
height : 每个条形的高度(与 X 对应的向量) 高度可以负数哦(图倒过来看就正的了)
width : 每个条形的宽度,默认 0.8
bottom : 每个条形底部的 Y 坐标,默认 0
label : 每类条形的标签
align : 每个条形与X坐标的对齐样式,默认是 ’center‘,还可以为 ‘edge’
color 或 facecolor(简称fc) : 柱的颜色,‘r’,‘g’,‘b’,‘c’,‘y’,…
edgecolor : 条形的边缘线颜色,‘r’,‘g’,‘b’,‘c’,‘y’,…
linestyle : 条形的边缘线样式,有{’/’, ‘’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’}
linewidth : 条形的边缘线宽度
xerr/yerr : 水平/垂直误差线长度 (每个条形的顶端中部画误差线)
ecolor : 水平/垂直误差线长颜色
hatch : 填充图案样式,有 {’/’, ‘’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’}
visible : 是否显示,默认 True 即显示条形图
例:
import numpy as np
import matplotlib.pyplot as plt
X = ['G1','G2','G3','G4','G5'] # X 轴标签
A = [20, 35, 30, 35, 27] #A 类高度
B = [25, 32, 34, 20, 25] #B 类高度
aerr = [2, 3, 4, 2, 2] #误差线长度
berr = [3, 5, 2, 3, 3] #误差线长度
fig= plt.figure(figsize=(8,6))
ax = fig.add_subplot()
# A 类的条形图
ax.bar(X, #每个条形的 X 坐标标签
A, #每个条形的高度
yerr=aerr, #垂直误差线长度
ecolor = "yellow", #垂直误差线长颜色
width = 0.9, #每个条形的宽度
label = "Class A", #每类条形的标签
color = "green", #条形的颜色
edgecolor = "red", #条形的边缘线颜色
linestyle = ":", #条形的边缘线样式
linewidth = 3.5, #条形的边缘线宽度
hatch = "/" #填充图案样式
) # plt.bar 也行
# B 类的条形图,底部高度应该在A类上方。其余具体属性均没设置。
ax.bar(X,B,yerr=berr,bottom=A,label="Class B") # plt.bar 也行
ax.set_ylabel("Scores") ## plt.ylabel() 也行
ax.set_title("Scores by Class A & B") ## plt.title() 也行
ax.legend() ## plt.legend() 也行
plt.show()
结果:
上面的条形图可以水平合并。
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
A = [20, 34, 30, 35, 27]
B = [25, 32, 34, 20, 25]
x = np.arange(len(labels))
width = 0.35 #条形图宽度
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot()
Afig = ax.bar(x - width/2, A, width, label='Class A')
Bfig = ax.bar(x + width/2, B, width, label='Class B')
ax.set_ylabel('Scores')
ax.set_title('Scores by Class A & B')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
def autolabel(rects): #每个条形顶部写出高度,接收参数bar对象
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(Afig)
autolabel(Bfig)
fig.tight_layout()
plt.show()
其中 annotate函数后面会详细写。
结果:
水平条形图可以利用**plt.barh()**对象
语法:plt.barh(y, width, height=0.8, left=None, *, align=‘center’, **kwargs)
参数与上面几乎一样,完全可以对比。
例:
import numpy as np
import matplotlib.pyplot as plt
Y = ['G1','G2','G3','G4','G5'] # Y 轴标签
A = [20, 35, 30, 35, 27] #高度
aerr = [2, 3, 4, 2, 2] #误差线长度
fig= plt.figure(figsize=(8,6))
ax = fig.add_subplot()
ax.barh(Y, #每个条形的 X 坐标标签
A, #每个条形的高度
xerr=aerr, #垂直误差线长度
ecolor = "black", #垂直误差线长颜色
label = "Class A", #每类条形的标签
color = "blue", #条形的颜色
edgecolor = "red", #条形的边缘线颜色
linestyle = ":", #条形的边缘线样式
linewidth = 3.5, #条形的边缘线宽度
hatch = "/" #填充图案样式
) # plt.barh 也行
ax.set_xlabel("Scores") ## plt.ylabel() 也行
ax.set_title("Scores by Class A & B") ## plt.title() 也行
ax.legend() ## plt.legend() 也行
plt.show(