Matplotlib:绘图和可视化

一、介绍

  • matplotlib是一个强大的python绘图和数据可视化的工具包
  • 安装方法:pip install matplotlib
  • 引用方法:import matplotlib.pyplot as plt
  • 绘图函数:plt.plot()
  • 显示函数:plt.show()

 

二、matplotlib

plot函数:绘制折线图
  • 线型linestyle(-,-.,--,.,)
  • 点型marker(v,^,s,*,H,+,x,D,o,...) 
  • 颜色color(b,g,r,y,k,w,...) 

 

示例:
 
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
 
#一条折线
plt.plot([0,1,2,3],[4,7,9,13],marker='.',linestyle='-',color='#000000')
result:

 

#两条折线

plt.plot([1,2,3,5])
plt.plot([2,7,21,3,76])

 

#pandas模块对plot的支持

df = pd.read_csv("601318.csv",parse_dates=['date'], index_col='date')

     [['open','close','high','low']]

df.plot()
plt.show()

result:

 
matplotlib-图像标注
  • 设置图像标注:plt.title()
  • 设置x轴名称:plt.xlabel()
  • 设置y轴名称:plt.ylabel()
  • 设置x轴范围:plt.xlim()
  • 设置y轴范围:plt.ylim()
  • 设置x轴刻度:plt.xticks()
  • 设置y轴刻度:plt.yticks()
  • 设置曲线图例:plt.legend()

 

示例:
#各个参数在图上的显示
plt.plot([1,3,4,5])
plt.plot([5,4,2,3])
plt.title('Graph 1')
plt.xlabel('X')
plt.ylabel('Y')
plt.xlim(0,3)
plt.ylim(1,5)
plt.xticks(np.arange(4))
plt.legend(['A','B'])

result:

#绘制数学图像
#使用matplotlib模块在一个窗口绘制数学函数y=x,y=x2,y=3x3+5x2+2x+1的图像,
使用不同颜色加以区别,并使用图例说明各个线代表什么函数

  x = np.linspace(-100,100,100000)
  y1 = x
  y2 = x ** 2
  y3 = 3*x**3 + 5*x**2+2*x+1
  plt.plot(x,y1, label="$y=x$")
  plt.plot(x,y2, label="$y=x^2$")
  plt.plot(x,y3, label="$y=3x^3+5x+2x+1$") # latex
  plt.ylim(-100,100)
  plt.xlim(-100,100)
  plt.legend()

  result:

  



matplotlib-画布与子图

  画布:figure
      fig=plt.figure()
  图:subplot
ax1=fig.add.subplot(2,2,1)
  调节子图间距:
       subplots_adjust(left,botton,right,top,wspace,hspace)

示例:

  %matplotlib auto

  fig = plt.figure()

  ax = fig.add_subplot(2,2,1)

  ax2 = fig.add_subplot(2,2,2)

  ax.plot([1,3,7])

  ax2.plot([2,5,8])
  plt.show()

  result:


 

matplotlib-支持的图类型
  • plt.plot(x,y,fmt,...) #坐标图
  • plt.boxplot(data,notch,position) #箱型图
  • plt.bar(width,bottom,left,height) #条形图
  • plt.barh(width,bottom,left,height) #横向条形图
  • plt.polar(theta,r) #极坐标图
  • plt.pie(data,explode) #饼图
  • plt.psd(x,NFFT=256,pad_to,Fs) #功率谱密度图
  • plt.specgram(x,NFFT=256,pad_to,F)#谱图
  • plt.cohere(x,y,NFFT=256,fs) #X-Y相关性函数
  • plt.scatter(x,y) #散点图
  • plt.step(x,y,where) #步阶图
  • plt.hist(x,bins,normed) #直方图
示例:

1)横向条形图
  %matplotlib inline
  plt.barh(np.arange(3),[2,6,10])
  plt.yticks(np.arange(3),['Jan','Feb',"Mar"])
  result:
  
(2)饼图
  plt.pie([1,2,3], labels=['a','b','c'],autopct='%.2f%%', explode=[0.2,0.0,0.0])
  plt.axis('equal')
  result:

(3)直方图
  plt.hist(x,500)
  plt.show()
  result:

 

posted @ 2018-02-26 20:38  星雨5213  阅读(172)  评论(0)    收藏  举报