python数据可视化之matplotlib
matplotlib模块依赖于numpy模块和tkinter模块,可以绘制多种形式的图形,包括线图、直方图、饼状图、散点图、误差线图等等。
(1) 绘制带有中文标签和图例的图
import numpy as np
import pylab as pl
import matplotlib.font_manager as fm
myfont = fm.FontProperties(fname=r'C:\Windows\Fonts\STKAITI.ttf') #设置字体
t = np.arange(0.0, 2.0*np.pi, 0.01) # 自变量取值范围
s = np.sin(t) # 计算正弦函数值
z = np.cos(t) # 计算余弦函数值
pl.plot(t, s, label='正弦')
pl.plot(t, z, label='余弦')
pl.xlabel('x-变量', fontproperties='STKAITI', fontsize=18) # 设置x标签
pl.ylabel('y-正弦余弦函数值', fontproperties='simhei', fontsize=18)
pl.title('sin-cos函数图像', fontproperties='STLITI', fontsize=24)
pl.legend(prop=myfont) # 设置图例
pl.show()
(2) 绘制散点图
>>> a = np.arange(0, 2.0*np.pi, 0.1)
>>> b = np.cos(a)
>>> pl.scatter(a,b)
>>> pl.show()
- 修改散点符号与大小
>>> pl.scatter(a,b,s=20,marker='+')
>>> pl.show()
- 修改线宽
>>> pl.scatter(a,b,s=20,linewidths=5,marker='+')
>>> pl.show()
- 修改颜色
>>> import matplotlib.pylab as pl
>>> import numpy as np
>>> x = np.random.random(100)
>>> y = np.random.random(100)
>>> pl.scatter(x,y,s=x*500,c=u'r',marker=u'*')
# s指大小,c指颜色,marker指符号形状
>>> pl.show()
(3) 绘制饼状图
import numpy as np
import matplotlib.pyplot as plt
#The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
colors = ['yellowgreen', 'gold', '#FF0000', 'lightcoral']
explode = (0, 0.1, 0, 0.1) # 使饼状图中第2片和第4片裂开
fig = plt.figure()
ax = fig.gca()
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
radius=0.25, center=(0, 0), frame=True) # autopct设置饼内百分比的格式
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=45,
radius=0.25, center=(1, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
radius=0.25, center=(0, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
autopct='%1.2f%%', shadow=False, startangle=135,
radius=0.35, center=(1, 0), frame=True)
ax.set_xticks([0, 1]) # 设置坐标轴刻度
ax.set_yticks([0, 1])
ax.set_xticklabels(["Sunny", "Cloudy"]) # 设置坐标轴刻度上的标签
ax.set_yticklabels(["Dry", "Rainy"])
ax.set_xlim((-0.5, 1.5)) # 设置坐标轴跨度
ax.set_ylim((-0.5, 1.5))
ax.set_aspect('equal') # 设置纵横比相等
plt.show()
(4) 使用pyplot绘制,多个图形在一起显示
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 500)
y = np.sin(x)
z = np.cos(x*x)
plt.figure(figsize=(8,4))
# 标签前后加$将使用内嵌的LaTex引擎将其显示为公式
plt.plot(x,y,label='$sin(x)$',color='red',linewidth=2) # 红色,2个像素宽
plt.plot(x,z,'b--',label='$cos(x^2)$') # 蓝色,虚线
plt.xlabel('Time(s)')
plt.ylabel('Volt')
plt.title('Sin and Cos figure using pyplot')
plt.ylim(-1.2,1.2)
plt.legend() # 显示图例
plt.show() # 显示绘图窗口
(5) 使用pyplot绘制,多个图形单独显示
import numpy as np
import matplotlib.pyplot as plt
x= np.linspace(0, 2*np.pi, 500) # 创建自变量数组
y1 = np.sin(x) # 创建函数值数组
y2 = np.cos(x)
y3 = np.sin(x*x)
plt.figure(1) # 创建图形
ax1 = plt.subplot(2,2,1) # 第一行第一列图形
ax2 = plt.subplot(2,2,2) # 第一行第二列图形
ax3 = plt.subplot(212, facecolor='y') # 第二行
plt.sca(ax1) # 选择ax1
plt.plot(x,y1,color='red') # 绘制红色曲线
plt.ylim(-1.2,1.2) # 限制y坐标轴范围
plt.sca(ax2) # 选择ax2
plt.plot(x,y2,'b--') # 绘制蓝色曲线
plt.ylim(-1.2,1.2)
plt.sca(ax3) # 选择ax3
plt.plot(x,y3,'g--')
plt.ylim(-1.2,1.2)
plt.show()
(6) 绘制三维图形
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
x,y = np.mgrid[-2:2:20j, -2:2:20j] # 步长使用虚数
# 虚部表示点的个数
# 并且包含end
z = 50 * np.sin(x+y) # 测试数据
ax = plt.subplot(111, projection='3d') # 三维图形
ax.plot_surface(x,y,z,rstride=2, cstride=1, cmap=plt.cm.Blues_r)
ax.set_xlabel('X') # 设置坐标轴标签
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
import pylab as pl
import numpy as np
import mpl_toolkits.mplot3d
rho, theta = np.mgrid[0:1:40j, 0:2*np.pi:40j]
z = rho**2
x = rho*np.cos(theta)
y = rho*np.sin(theta)
ax = pl.subplot(111, projection='3d')
ax.plot_surface(x,y,z)
pl.show()
(7) 绘制三维曲线
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
mpl.rcParams['legend.fontsize'] = 10 # 图例字号
fig = plt.figure()
ax = fig.gca(projection='3d') # 三维图形
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-4, 4, 100)*0.3 # 测试数据
r = z**3 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()
plt.show()