先将matplot模块导入,并缩写:
import matplotlib as mpl
有时候只需要其中的一部分:
import matplotlib.pyplot as plt
二维图:
折线图plt.plot()
散点图plt.scatter():
绘制一个y=sin(x)的图形,假设取101个点,以x为横轴,y为纵轴。
>>> x=np.linspace(start=0,stop=5,num=101) >>> y=np.sin(x) >>> plt.plot(x,y) [<matplotlib.lines.Line2D object at 0x00000214D7338518>] >>> plt.show()
plt.plot()已经得到了这个图,但是需要用plt.show()来显示。
对于得到的图像可以用:
plt.savefigure(*arg,**kwarg) 来保存图像,,也可以得到的图像中的保存按钮保存。
>>> plt.savefig("C:\\Users\\C\\Desktop\\pr\\Fig_2.png")
在一张图上显示两个函数:
坐标范围:
x轴的坐标范围: plt.xlim(a,b) # 在(a,b)范围内 plt.xlim(-3,3)
y轴的坐标范围: plt.ylim(a,b) # 在(a,b)范围内 plt.ylim(,-4,4)
plt.plot(*arg,**kwarg)
设置折线颜色,线的格式: plt.plot(x,y,color='red',linestyle='--') # 红色虚线
坐标轴命名:
x轴:plt.xlabel("x axis")
y轴 plt.ylabel("sin(y)")
可以在图片上上说明,解释折线,
plt.plot(x,y,label='说明文字')
plt.legend() # 显示说明文字
>>> plt.plot(x,y,label='sinx') [<matplotlib.lines.Line2D object at 0x0000019EEE3F3EF0>] >>> plt.legend() <matplotlib.legend.Legend object at 0x0000019EEE3F32E8> >>> plt.show()
加标题 plt.title('标题')
plt.figure("图片名字") # 给生成的图片命名
plt.figure(num=None,figsize=None,dpi=None,facecolor=None,edgecolor=None,frameon=True,clear=False,**kwargs)
实例:
# -*- coding:cp936 -*- # from numpy import * import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt x=np.linspace(-2,2,100) y=2*np.sin(x) z=np.cos(x) plt.figure('C:\\Users\\C\\Desktop\\pr\\figure_1.png') # 图表命名 plt.plot(x,y,label='sinx') # 定义折线的颜色和格式 plt.legend() # legend() 只管到上一个plot(),如果没有这个legend()figure_1的label就不存在,title也是同理 plt.title("title1") plt.figure("C:\\Users\\C\\Desktop\\pr\\figure_2.png") #第二张图命名 plt.plot(x,z,label='cosx') plt.title("title2") plt.legend() # 画散点图,同时和第一张图的折线出现在一张图上 w=y+np.random.normal(scale=0.3,size=100) # size和x取的点数要相同 plt.figure("C:\\Users\\C\\Desktop\\pr\\figure_3.png") # 第三张图 plt.scatter(x,w,label='scatter') plt.plot(x,y,label='sinx') #plt.xlabel=('x') # 设置坐标没有用 #plt.ylabel=('y') plt.title("title3") plt.legend() # 显示label plt.show()
生成:
子图:
axes 和subplot函数
fig=plt.figure()
ax1=fig.add_subplot(221)
ax2=fig.add_subplot(222)
ax3=fig.add_subplot(223)
ax4=fig.add_subplot(224)
生成(2x2)四个子图,位置分别是1,2,3,4.