用Pandas作圖

來自:http://cloga.info/python/2014/02/23/Plotting_with_Pandas/#wat_e_12612920-6fe4-464e-a2b0-3b1f13c1a4f6_zss_

關於Pandas的基本使用介紹,請查看另一篇博文: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')
<matplotlib.legend.Legend at 0x10b9c7610>

png

這是Series上的plot方法,通過DataFrame的plot方法,你可以將男生和女生出生數量的趨勢圖畫在一起。

present_year.plot()
<matplotlib.axes.AxesSubplot at 0x108ce4910>

png

present_year.girls.plot(color='g')
present_year.boys.plot(color='b')
plt.legend(loc='best')
<matplotlib.legend.Legend at 0x10999e510>

png

可以看到DataFrame提供plot方法與在多個Series調用多次plot方法的效果是一致。

present_year[:10].plot(kind='bar')
<matplotlib.axes.AxesSubplot at 0x10ab31390>

png

plot默認生成是曲線圖,你可以通過kind參數生成其他的圖形,可選的值爲:line, bar, barh, kde, density, scatter。

present_year[:10].plot(kind='bar')
<matplotlib.axes.AxesSubplot at 0x10bb35890>

png

present_year[:10].plot(kind='barh')
<matplotlib.axes.AxesSubplot at 0x10eb01890>

png

如果你需要累積的柱狀圖,則只需要指定stacked=True。

present_year[:10].plot(kind='bar', stacked=True)
<matplotlib.axes.AxesSubplot at 0x10bbdb3d0>

png

製作相對的累積柱狀圖,需要一點小技巧。

首先需要計算每一行的彙總值,可以在DataFrame上直接調用sum方法,參數爲1,表示計算行的彙總。默認爲0,表示計算列的彙總。

present_year.sum(1)[:5]
year
1940    2360399
1941    2513427
1942    2808996
1943    2936860
1944    2794800
dtype: int64

有了每一行的彙總值之後,再用每個元素除以對應行的彙總值就可以得出需要的數據。這裏可以使用DataFrame的div函數,同樣要指定axis的值爲0。

present_year.div(present_year.sum(1),axis=0)[:10].plot(kind='barh', stacked=True)
<matplotlib.axes.AxesSubplot at 0x113223290>

png

散點圖和相關

plot也可以畫出散點圖。使用kind='scatter', x和y指定x軸和y軸使用的字段。

present_year.plot(x='boys', y='girls', kind='scatter')
<matplotlib.axes.AxesSubplot at 0x1141c9810>

png

再來載入一下鳶尾花數據。

url_2 = 'https://raw.github.com/pydata/pandas/master/pandas/tests/data/iris.csv'
iris = pd.read_csv(url_2)
iris.head(5)
  SepalLength SepalWidth PetalLength PetalWidth Name
0 5.1 3.5 1.4 0.2 Iris-setosa
1 4.9 3.0 1.4 0.2 Iris-setosa
2 4.7 3.2 1.3 0.2 Iris-setosa
3 4.6 3.1 1.5 0.2 Iris-setosa
4 5.0 3.6 1.4 0.2 Iris-setosa

5 rows × 5 columns

iris.corr()
  SepalLength SepalWidth PetalLength PetalWidth
SepalLength 1.000000 -0.109369 0.871754 0.817954
SepalWidth -0.109369 1.000000 -0.420516 -0.356544
PetalLength 0.871754 -0.420516 1.000000 0.962757
PetalWidth 0.817954 -0.356544 0.962757 1.000000

4 rows × 4 columns

from pandas.tools.plotting import scatter_matrix
scatter_matrix(iris, alpha=0.2, figsize=(6, 6), diagonal='kde')
array([[<matplotlib.axes.AxesSubplot object at 0x1141e5290>,
        <matplotlib.axes.AxesSubplot object at 0x114313610>,
        <matplotlib.axes.AxesSubplot object at 0x11433fbd0>,
        <matplotlib.axes.AxesSubplot object at 0x114328e10>],
       [<matplotlib.axes.AxesSubplot object at 0x11411f350>,
        <matplotlib.axes.AxesSubplot object at 0x114198690>,
        <matplotlib.axes.AxesSubplot object at 0x114181b90>,
        <matplotlib.axes.AxesSubplot object at 0x11436eb90>],
       [<matplotlib.axes.AxesSubplot object at 0x11438ced0>,
        <matplotlib.axes.AxesSubplot object at 0x114378310>,
        <matplotlib.axes.AxesSubplot object at 0x1143e34d0>,
        <matplotlib.axes.AxesSubplot object at 0x114d0a810>],
       [<matplotlib.axes.AxesSubplot object at 0x1143ecd50>,
        <matplotlib.axes.AxesSubplot object at 0x114d40e90>,
        <matplotlib.axes.AxesSubplot object at 0x114d63210>,
        <matplotlib.axes.AxesSubplot object at 0x114d4a2d0>]], dtype=object)

png

箱圖

DataFrame提供了boxplot方法可以用來畫箱圖。

iris.boxplot()
{'boxes': [<matplotlib.lines.Line2D at 0x1141439d0>,
  <matplotlib.lines.Line2D at 0x11416c1d0>,
  <matplotlib.lines.Line2D at 0x1141559d0>,
  <matplotlib.lines.Line2D at 0x11414b210>],
 'caps': [<matplotlib.lines.Line2D at 0x11416af90>,
  <matplotlib.lines.Line2D at 0x1141434d0>,
  <matplotlib.lines.Line2D at 0x114172790>,
  <matplotlib.lines.Line2D at 0x114172c90>,
  <matplotlib.lines.Line2D at 0x114153f90>,
  <matplotlib.lines.Line2D at 0x1141554d0>,
  <matplotlib.lines.Line2D at 0x11414f7d0>,
  <matplotlib.lines.Line2D at 0x11414fcd0>],
 'fliers': [<matplotlib.lines.Line2D at 0x114145410>,
  <matplotlib.lines.Line2D at 0x114145b50>,
  <matplotlib.lines.Line2D at 0x11416cbd0>,
  <matplotlib.lines.Line2D at 0x1141530d0>,
  <matplotlib.lines.Line2D at 0x114151410>,
  <matplotlib.lines.Line2D at 0x114151b90>,
  <matplotlib.lines.Line2D at 0x11414bc10>,
  <matplotlib.lines.Line2D at 0x1141743d0>],
 'medians': [<matplotlib.lines.Line2D at 0x114143ed0>,
  <matplotlib.lines.Line2D at 0x11416c6d0>,
  <matplotlib.lines.Line2D at 0x114155ed0>,
  <matplotlib.lines.Line2D at 0x11414b710>],
 'whiskers': [<matplotlib.lines.Line2D at 0x11416a7d0>,
  <matplotlib.lines.Line2D at 0x11416aa10>,
  <matplotlib.lines.Line2D at 0x114172050>,
  <matplotlib.lines.Line2D at 0x114172290>,
  <matplotlib.lines.Line2D at 0x114153590>,
  <matplotlib.lines.Line2D at 0x114153a90>,
  <matplotlib.lines.Line2D at 0x11414f090>,
  <matplotlib.lines.Line2D at 0x11414f2d0>]}

png

通過by參數可以計算不同分組情況下,各個字段的箱圖。

iris.boxplot(by='Name', figsize=(8, 8))
array([[<matplotlib.axes.AxesSubplot object at 0x120dd8f50>,
        <matplotlib.axes.AxesSubplot object at 0x1218d3410>],
       [<matplotlib.axes.AxesSubplot object at 0x1218f47d0>,
        <matplotlib.axes.AxesSubplot object at 0x1218de490>]], dtype=object)

png

直方圖和概率密度分佈

iris.ix[:,:-1].hist()
iris.plot(kind='kde')
<matplotlib.axes.AxesSubplot at 0x117263890>

png

png

多變量的可視化

Radviz

from pandas.tools.plotting import radviz
radviz(iris, 'Name')
<matplotlib.axes.AxesSubplot at 0x11412e550>

png

Andrews Curves

from pandas.tools.plotting import andrews_curves
andrews_curves(iris, 'Name')
<matplotlib.axes.AxesSubplot at 0x1218e2d50>

png

Parallel Coordinates

from pandas.tools.plotting import parallel_coordinates
parallel_coordinates(iris, 'Name')
<matplotlib.axes.AxesSubplot at 0x1224b36d0>

png

你也可以查看本文的ipython notebook版本:http://nbviewer.ipython.org/gist/cloga/9171281


發佈了24 篇原創文章 · 獲贊 17 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章