2.1.5.Python for Data Visual Visualization - Pandas Built-in Data Visualization

1.使用library
import numpy as np
import pandas as pd
將matplotlib的圖表直接嵌入到Notebook之中
%matplotlib inline
2.資料判讀與讀取
讀取資料格式 (df1)
由於df1的資料有時間這個索引值, 因此必須指定index為0
讀取資料
df1 = pd.read_csv('df1', index_col = 0) df1.head()
讀取資料格式 (df2)
由於此資料沒有索引值, 不需指定index
讀取資料
df2 = pd.read_csv('df2') df2.head()
3.Setting before plot
一般會配合Matplotlib一起使用
設定圖的大小
plt.figure(figsize=(10,6))
4.Histogram plot
將df1的資料畫成長條圖
df1['A'].hist(bins = 30)

也可以用
df1['A'].plot(kind='hist', bins = 30)

可以搭配filter使用, 例如
df[df[B] == 1][A].plot(kind='hist', bins = 30)
用hist比較不同性質的資料
df = pd.read_csv('loan_data.csv')
df.head()
plt.figure()
df[df['credit.policy']==1]['fico'].plot(kind = 'hist', bins = 30, color = 'blue', alpha = 0.5, label = 'Credit.Policy=1')
df[df['credit.policy']==0]['fico'].plot(kind = 'hist', bins = 30, color = 'red', alpha = 0.5, label = 'Credit.Policy=0')
plt.legend()
plt.xlabel('FICO')

5.Area plot
alpha為透明度參數
df2.plot.area(alpha = 0.4)

6.Line plot
基本用法
df1.plot.line(x=df1.index, y = 'B')

6.Bar plot
基本用法
df2.plot.bar(alpha = 0.4)

stacked
df2.plot.bar(alpha = 0.4, stacked = True)

7.Scatter plot
基本用法
df1.plot.scatter(x='A', y='B')

將原始資料作為色調值的來源
df1.plot.scatter(x='A', y='B', c='C', cmap='coolwarm')

將原始資料作為尺度的來源
df1.plot.scatter(x='A', y='B', s=df1['C']*100)

8.Box plot
基本用法, 關於boxplot的定義可以參考此篇筆記
df2.plot.box()

將兩資料的box plot畫在一起
df1[['A','B']].plot.box()

9.Density plot
基本用法
df2.plot.density()

改變線條的style (width, size)
df2.plot.density(lw=5,ls='--')

10.Hexbin plot
基本用法
df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])df.plot.hexbin(x='a', y='b', gridsize=25, cmap='coolwarm')

Last updated
Was this helpful?