matplotlib作图方法

Matplotlib python作图


导入需要的包numpy和matpl

import numpy as np
import matplotlib.pyplot as plt

作图实例

x=np.arange(1,10)      #x=array([1, 2, 3, 4, 5, 6, 7, 8, 9])
y=3*x+5                #y=array([ 8, 11, 14, 17, 20, 23, 26, 29, 32])
plt.plot(x,y)          #[]
plt.show()

matplotlib作图方法_第1张图片
[ − π , π ] [-\pi,\pi] [π,π]上y=sinx的图

x=np.arange(-np.pi,np.pi+0.01,0.01)
y=np.sin(x)
plt.plot(x,y)
plt.show()

matplotlib作图方法_第2张图片

plt.title("     ")     #改变标题
plt.xlabel("     "     #改变x轴名称
plt.ylabel("    ")     #改变y轴名称

在plt.plot()中添加不同的格式字符能达到不同的显示效果

字符 效果
“-” 实线
“–” 虚线
“-.” 点划线
“g” 绿色
“r” 红色
#颜色用plt.plot(color="   ")
#虚线或实现用plt.plot(linestyle="   ")
#要在同一张图中作两张子图,需要plt.subplot()
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(-3*np.pi,3*np.pi,0.1)
y1=np.cos(x)
y2=np.sin(x)
plt.subplot(2,2,1) #高为2,宽为1,第1张图
plt.plot(x,y1)
plt.subplot(2,2,2) #高为2,宽为1,第2张图
plt.plot(x,y2)
plt.show()

matplotlib作图方法_第3张图片

#同时作出两张图,需要在代码中添加 plt.figure()
x=np.arange(1,10)
y1=3*x
y2=np.sin(x)
plt.figure()
plt.plot(x,y1)

plt.figure()
plt.plot(x,y2)
plt.show()
#plt.figure("   ")中可填入figure名称
#figure(figsize=(a,b))可调整大小

matplotlib作图方法_第4张图片

设置坐标轴

plt.xlim((left,right)) #给出范围
plt.xlim(left=3)   #只给出左边的界限
plt.xlim(right=10) #只给出右边的界限

柱状图

plt.bar(x,y)

3D图

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig=plt.figure()
ax=Axes3D(fig)
X=np.arange(-4,4,0.25)
Y=np.arange(-4,4,0.25)
X,Y=np.meshgrid(X,Y) #将两个一维数组变成二维数组
>>> X
array([[-4.  , -3.95, -3.9 , ...,  3.85,  3.9 ,  3.95],
       [-4.  , -3.95, -3.9 , ...,  3.85,  3.9 ,  3.95],
       [-4.  , -3.95, -3.9 , ...,  3.85,  3.9 ,  3.95],
       ...,
       [-4.  , -3.95, -3.9 , ...,  3.85,  3.9 ,  3.95],
       [-4.  , -3.95, -3.9 , ...,  3.85,  3.9 ,  3.95],
       [-4.  , -3.95, -3.9 , ...,  3.85,  3.9 ,  3.95]])
>>> Y
array([[-4.  , -4.  , -4.  , ..., -4.  , -4.  , -4.  ],
       [-3.95, -3.95, -3.95, ..., -3.95, -3.95, -3.95],
       [-3.9 , -3.9 , -3.9 , ..., -3.9 , -3.9 , -3.9 ],
       ...,
       [ 3.85,  3.85,  3.85, ...,  3.85,  3.85,  3.85],
       [ 3.9 ,  3.9 ,  3.9 , ...,  3.9 ,  3.9 ,  3.9 ],
       [ 3.95,  3.95,  3.95, ...,  3.95,  3.95,  3.95]])


R=np.sqrt(X*X+Y*Y)
Z=np.sin(R)
ax.plot_surface(X,Y,Z,cmap=plt.get_cmap('rainbow'))
plt.show()

你可能感兴趣的:(python,作图)