matplotlib笔记

Python数据可视化—matplotlib笔记

在参加数据挖掘竞赛中,经常需要对数据进行可视化。今天有空就对数据可视化— matplotlib这块内容系统的整理下,方便查找使用。本文来自于对《利用python进行数据分析》以及网上一些博客的总结。


1  matplotlib简介

matplotlib是Pythom可视化程序库的泰斗,经过几十年它仍然是Python使用者最常用的画图库。有许多别的程序库都是建立在它的基础上或直接调用它,比如pandas和seaborn就是matplotlib的外包,它们让你使用更少的代码去使用matplotlib的方法。Gallery页面中有上百幅缩略图,打开之后都有源程序,非常适合学习matplotlib。

利用IPython --pylab可以进入Pylab模式,已经导入了matplotlib库和相关软件包(如numpy和scipy),如果安装了anconda,可以按(win + R)打开运行窗口,输入ipython --pylab启动IPython。在notebook模式下可以通过命令%matplotlib inline 使图片内嵌在交互窗口。

2  图和子图的建立

2.1  导入matplotlib
import matplotlib.pyplot as plt
  
  

2.2  建立图和子图方式一
plt.plot( )会在最近的一个图上进行绘制

  
  
  1. from numpy.random import randn
  2. fig = plt.figure(figsize = ( 8, 4)) #设置图的大小
  3. ax1 = fig.add_subplot( 2, 2, 1)
  4. ax2 = fig.add_subplot( 2, 2, 2)
  5. ax3 = fig.add_subplot( 2, 1, 2)
  6. ax3.plot(randn( 50).cumsum(), 'k--') # plt.plot(randn(50).cumsum(),'k--')等效
  7. ax1.hist(randn( 100),bins = 10, color = 'b', alpha = 0.3) #bins 分成多少间隔 alpha 透明度
  8. ax2.scatter(np.arange( 30),np.arange( 30) + 3*randn( 30))
  9. plt.show()



2.3 建立子图方式二

  
  
  1. from numpy.random import randn
  2. fig, axes = plt.subplots( 2, 2) #以数组方式访问
  3. t = np.arange( 0., 5., 0.2)
  4. axes[ 0, 0].plot(t, t, 'r-o', t, t** 2, 'bs', t, t** 3, 'g^') #同时绘制多条曲线
  5. axes[ 1, 1].plot(randn( 40).cumsum(), 'b--')
  6. plt.show()
2.4 主题设置
使用style.use()函数

  
  
  1. df_iris = pd.read_csv( '../input/iris.csv')
  2. plt.style.use( 'ggplot') #'fivethirtyeight','ggplot','dark_background','bmh'
  3. df_iris.hist( 'sepal length')
  4. plt.show()


3  颜色、标记、线型、刻度、标签和图例


  
  
  1. from numpy.random import randn
  2. fig = plt.figure()
  3. ax1 = fig.add_subplot( 1, 1, 1)
  4. ax1.plot(randn( 30).cumsum(),color = 'b',linestyle = '--',marker = 'o',label = '$cumsum$') # 线型 可以直接'k--o'
  5. ax1.set_xlim( 10, 25)
  6. ax1.set_title( 'My first plot')
  7. ax1.set_xlabel( 'Stages')
  8. plt.legend(loc = 'best') #把图放在不碍事的地方 xticks([])设置刻度
  9. plt.show()
与下面程序等价

  
  
  1. from numpy.random import randn
  2. fig = plt.figure()
  3. ax1 = fig.add_subplot( 1, 1, 1)
  4. ax1.plot(randn( 30).cumsum(),color = 'b',linestyle = '--',marker = 'o',label = '$cumsum$') #图标可以使用latex内嵌公式
  5. plt.xlim( 10, 25) #plt.axis([10,25,0,10])对x,y轴范围同时进行设置
  6. plt.title( 'My first plot')
  7. plt.xlabel( 'Stages')
  8. plt.legend(loc = 'best')
  9. plt.show()



4  pandas中的绘图函数

在pandas中,我们具有行标签,列标签以及分组信息。这也就是说,要制作一张完整的图表,原本需要一大堆的matplotlib代码,现在只需一两条简洁的语句就可以了。pandas有很多能够利用DataFrame对象数据组织特点来创建标准图表的高级绘图方法。
4.1  线型图

  
  
  1. from numpy.random import randn
  2. fig, axes = plt.subplots( 1, 2)
  3. s = pd.Series(randn( 10).cumsum(),index = np.arange( 0, 100, 10))
  4. s.plot(ax = axes[ 0]) # ax参数选择子图
  5. df = pd.DataFrame(randn( 10, 3).cumsum( 0),columns = [ 'A', 'B', 'C'],index = np.arange( 0, 100, 10))
  6. df.plot(ax = axes[ 1])
  7. plt.show()
4.2 柱状图

  
  
  1. from numpy.random import rand
  2. fig, axes = plt.subplots( 1, 2)
  3. data = pd.Series(rand( 16),index = list( 'abcdefghijklmnop'))
  4. data.plot(kind = 'bar', ax = axes[ 0], color = 'b', alpha = 0.7) #kind选择图表类型 'bar' 垂直柱状图
  5. data.plot(kind = 'barh', ax = axes[ 1], color = 'b', alpha = 0.7) # 'barh' 水平柱状图
  6. plt.show()

  
  
  1. from numpy.random import rand
  2. fig, axes = plt.subplots( 1, 2)
  3. data = pd.DataFrame(rand( 6, 4),
  4. index = [ 'one', 'two', 'three', 'four', 'five', 'six'],
  5. columns = pd.Index([ 'A', 'B', 'C', 'D'], name = 'Genus'))
  6. data.plot(kind = 'bar', ax = axes[ 0], alpha = 0.5)
  7. data.plot(kind = 'bar', ax = axes[ 1], stacked = True, alpha = 0.5)
  8. plt.show()

此外,柱状图有一个非常不错的用法,利用value_counts( )图形化显示Series中各值的出现概率,比如s.value_counts( ).plot(kind = 'bar')。
4.3 直方图和密度图

  
  
  1. from numpy.random import randn
  2. fig, axes = plt.subplots( 1, 2)
  3. data = pd.Series(randn( 100))
  4. data.hist(ax = axes[ 0], bins = 50) #直方图
  5. data.plot(kind = 'kde', ax = axes[ 1]) #密度图
  6. plt.show()


其实可以一次性制作多个直方图,layout参数的意思是将两个图分成两行一列,如果没有这个参数,默认会将全部的图放在同一行

  
  
  1. df_iris = pd.read_csv( '../input/iris.csv')
  2. columns = [ 'sepal length', 'sepal width', 'petal length', 'petal width']
  3. df_iris.hist(column=columns, layout=( 2, 2))
  4. plt.show()


4.4 箱型图
箱型图是基于五数概括法(最小值,第一个四分位数,第一个四分位数(中位数),第三个四分位数,最大值)的数据的一个图形汇总,还需要用到四分位数间距IQR = 第三个四分位数 - 第一个四分位数。

  
  
  1. df_iris = pd.read_csv( '../input/iris.csv') #['sepal length','sepal width','petal length','petal width','class']
  2. sample_size = df_iris[[ 'petal width', 'class']]
  3. sample_size.boxplot(by= 'class')
  4. plt.xticks(rotation= 90) #将X轴的坐标文字旋转90度,垂直显示
  5. plt.show()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值