数据可视化(一)-Matplotlib简易入门

本节的内容来源:https://www.dataquest.io/mission/10/plotting-basics

本节的数据来源:https://archive.ics.uci.edu/ml/datasets/Forest+Fires

原始数据展示(这张表记录了某个公园的火灾情况,X和Y代表的是坐标位置,area代表的是烧毁面积)

import pandas

forest_fires = pandas.read_csv('forest_fires.csv')

print(forest_fires.head(5))

Image 001

 

在使用matplotlib库的时候,都会默认地缩写为plt

import matplotlib.pyplot as plt

一个作图的过程分为三步:

1.初始化绘图数据

2.作图

3.展示该图

 

散点图

使用matplotlib.pyplot.scatter()方法来做散点图,第一个参数作为x轴,第二参数作为y轴,注意两个参数都只能是列表数据或者Series

# 使用列表数据作为坐标轴

import matplotlib.pyplot as plt

weight = [600,150,200,300,200,100,125,180]

height = [60,65,73,70,65,58,66,67]

plt.scatter(height, weight)

plt.show()

Image 003

# 使用Series作为坐标轴

#以风速数据(wind)作为x轴,烧毁面积(area)作为y轴,做出它们的散点图

plt.scatter(forest_fires["wind"], forest_fires["area"])

plt.show()

Image 002

可以留意到上面的两张图都没有图标题,也没有横坐标和纵坐标的文字说明,可以通过几个函数来添加相应的信息:

  • title() -- 添加图的表题
  • xlabel() -- 添加x轴的文字说明信息
  • ylabel() -- 添加y轴的文字说明信息
plt.scatter(forest_fires['wind'], forest_fires['area'])

plt.title('Wind speed vs fire area')

plt.xlabel('Wind speed when fire started')

plt.ylabel('Area consumed by fire')

plt.show()

Image 004

 

折线图

折线图使用matplotlib.pyplot.plot()函数来作图,参数的要求和上面的散点图一样,下面只举一个例子即可

# 使用列表数据作为坐标轴

age = [5, 10, 15, 20, 25, 30]

height = [25, 45, 65, 75, 75, 75]

plt.plot(age, height)

plt.title('Age vs Height')

plt.xlabel('age')

plt.ylabel('Height')

plt.show()

Image 005

 

条形图

使用matplotlib.pyplot.bar()函数来绘制垂直型的条形图,参数要求同上,下面只举一个例子

# 现在要按月份统计烧毁的面积

# 先做一个透视图,计算每个月的烧毁面积

area_by_month = forest_fires.pivot_table(index="month", values="area", aggfunc=numpy.sum)

Image 008

plt.bar(range(len(area_by_month)), area_by_month)

plt.title('Month vs Area')

plt.xlabel('month')

plt.ylabel('area')

plt.show()

Image 010

一定要注意,上图中的X轴对应数字并不代表月份,因为area_by_month中的数据是无序的

 

使用matplotlib.pyplot.barh()函数来绘制水平型的条形图,注意:与bar()函数最大的不同是X轴和Y轴是颠倒过来的

plt.barh(range(len(area_by_month)), area_by_month)

plt.title('Month vs Area')

plt.xlabel('area')

plt.ylabel('month')

plt.show()

Image 011

可以看到X轴与Y轴是颠倒过来的

 

使用不同的作图主题

可以选择使用不同的作图主题,使用style.use()函数即可

# 使用两种主题做一下对比

plt.style.use('fivethirtyeight')

plt.plot(forest_fires['rain'], forest_fires['area'])

plt.show()

Image 012

plt.style.use('ggplot')

plt.plot(forest_fires['rain'], forest_fires['area'])

plt.show()

Image 013

通常使用以下几种主题:

fivethirtyeight,ggplot,dark_background,bmh

posted @ 2016-03-01 21:33  kylinlin  阅读(12668)  评论(1编辑  收藏  举报