使用Python pandas作图

推荐使用ipython的pylab模式,如果要在ipython notebook中嵌入图片,则还需要指定pylab=inline。

ipython --pylab ##ipython的pylab模式
ipython notebook --pylab=inline ##notebook的inline模式
import pandas as pd

基本画图命令

Pandas通过整合matplotlib的相关功能实现了基于DataFrame的一些 作图功能。下面的数据是每年美国男女出生数据:

url = 'http://s3.amazonaws.com/assets.datacamp.com/course/dasi/present.txt'
present = pd.read_table(url, sep=' ')
present.shape
(63, 3)
present.columns
Index([u'year', u'boys', u'girls'], dtype='object')

可以看到这个数据集共有63条记录,共有三个字段:Year,boys,girls。为了简化计算将year作为索引。

present_year = present.set_index('year')

plot是画图的最主要方法,Series和DataFrame都有plot方法。

可以这样看一下男生出生比例的趋势图:

present_year['boys'].plot()
plt.legend(loc='best')

这里写图片描述

这是Series上的plot方法,通过DataFrame的plot方法,你可以将男生和女生出生数量的趋势图画在一起。

present_year.plot()

这里写图片描述

present_year.girls.plot(color='g')
present_year.boys.plot(color='b')
plt.legend(loc='best')

这里写图片描述

可以看到DataFrame提供plot方法与在多个Series调用多次plot方法的效果是一致。

present_year[:10].plot(kind='bar')

这里写图片描述

plot默认生成是曲线图,你可以通过kind参数生成其他的图形,可选的值为:line, bar, barh, kde, density, scatter。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值