python - matplotlib demo

平面图绘制
from matplotlib import pyplot as plt
import numpy as np
# linspace(x, y)产生一个有100个元素的行向量,其中的元素在区间[x, y]中等间隔分布。
# linspace(x, y, n)产生x和y之间等间隔的n个数,如果n = 1,返回结果为y。

x = np.linspace(-np.pi,np.pi)
plt.plot(x,np.cos(x),color='red')
plt.show()

# 颜色:英文字母、RGB数值、十六进制颜色等表示
# 线条样式 :(点状线) 、 -(实线)
# 点样式:.(圆点) 、 s (方形) 、 o(圆形)
x = np.linspace(0,2*np.pi,50)
plt.plot(x,np.sin(x),'c:' ,
         x,np.sin(x-np.pi/2),'b-.') # b-. 分别代表 颜色(蓝色)、线条样式(实线)、点样式(圆点)
plt.show()


x = np.random.randn(20)
y = np.random.randn(20)
x1 = np.random.randn(40)
y1 = np.random.randn(40)
# 绘制散点图
plt.scatter(x,y,s=50,color='b',marker='<',label='S1') # s为散点尺寸
plt.scatter(x1,y1,s=50,color='y',marker='o',alpha=0.2,label='S2') # alpha为透明度
plt.grid(True)  # 打开网格效果
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.legend()    # 图例
plt.title('My Scatter')
plt.show()


# 将多个图表放置于一张图中
x = np.linspace(0,2*np.pi,50)
plt.subplot(2,2,1)  # 子图总行数、列数、活跃区域id
plt.plot(x,np.sin(x),'b',label='sin(x)')
plt.legend()
plt.subplot(2,2,2)
plt.plot(x,np.cos(x),'r',label='cos(x)')
plt.legend()
plt.subplot(2,2,3)
plt.plot(x,np.exp(x),'k',label='exp(x)')
plt.legend()
plt.subplot(2,2,4)
plt.plot(x,np.arctan(x),'y',label='arctan(x)')
plt.legend()

plt.show()


# 条形图
x = np.arange(12)
y = np.random.rand(12)
labels = ['1','2','3','4','5','6','7','8','9','10','11','12']
plt.bar(x,y,color='blue',tick_label=labels)
# plt.barh(x,y,color='blue',tick_label=labels) # 横条
plt.title('bar graph')
plt.show()

# 饼图
size = [20,20,20,40]    # 各部分比例
plt.axis(aspect=1)
explode = [0.02,0.02,0.02,0.05] # 突出显示
plt.pie(size,labels=['A','B','C','D'],autopct='%.0f%%',explode=explode,shadow=True)
plt.show()

# 直方图
x = np.random.randn(1000)
plt.hist(x,200)
plt.show()

子图
python - matplotlib demo_第1张图片
饼图
python - matplotlib demo_第2张图片

3D图绘制
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()  # 定义figure
ax = Axes3D(fig)
x = np.arange(-2,2,0.1)
y = np.arange(-2,2,0.1)
X , Y = np.meshgrid(x,y) # 生成网格数据
Z = X ** 2 + Y ** 2
ax.plot_surface(X,Y,Z,cmap=plt.get_cmap('rainbow')) # 绘制3D曲面
ax.set_zlim(-1,10)  # z轴区间
plt.title('3D graph')
plt.show()

python - matplotlib demo_第3张图片

你可能感兴趣的:(python)