pandas繪圖指南

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

pandas繪圖

基本繪圖方法plot

Series.plot和DataFrame.plot是plt.plot的一個簡單包裝

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.head()
2000-01-01   -1.158434
2000-01-02   -1.234039
2000-01-03   -1.453900
2000-01-04   -1.969126
2000-01-05   -2.358607
Freq: D, dtype: float64
ts.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x11e848310>

DataFrame.plot是同時繪製每一列到同一個圖,並且附帶了標籤

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.head()
ABCD
2000-01-010.687417-0.943176-0.5624820.398902
2000-01-021.918521-0.743811-0.9749492.073606
2000-01-033.265497-2.0357230.7567341.309357
2000-01-044.643224-2.2330200.1468250.574324
2000-01-055.735268-3.2608421.4095481.479241
df.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x11ea35f50>

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-Jw1Faufq-1579503959330)(images/output_7_1.png)]

你可以使用plot中的x和y關鍵字繪製一列與另一列的關係:

df3 = pd.DataFrame(np.random.randn(1000, 2), columns=['B', 'C']).cumsum()
df3['A'] = pd.Series(list(range(len(df))))
df3.plot(x='A', y='B')
<matplotlib.axes._subplots.AxesSubplot at 0x11eb72b90>

其他繪圖

Series.plot或DataFrame.plot默認都是線圖,其他類型的圖需要修改參數kind,支持以下幾種類型的圖:

  • bar、barh
  • hist
  • box
  • kde、density
  • area
  • scatter
  • hexbin
  • pie
df.iloc[5].plot(kind='bar')
<matplotlib.axes._subplots.AxesSubplot at 0x11ec8bc10>

除了修改kind參數之外,還支持DataFrame.plot.<>,如 DataFrame.plot.bar 等價於 DataFrame.plot(kind=‘bar’)

df.iloc[5].plot.bar()
<matplotlib.axes._subplots.AxesSubplot at 0x11ed608d0>

除了以上兩種方式,有的繪圖類型還支持單獨的接口:

  • DataFrame.hist
  • DataFrame.boxplot
df.hist()
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x11ed685d0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x11ee54610>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x11eedfe10>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x11ef1f650>]],
      dtype=object)

條形圖

Series.plot.bar會繪製一個條形圖

plt.figure()
plt.axhline(0, color='k')
df.iloc[5].plot.bar()
<matplotlib.axes._subplots.AxesSubplot at 0x120bbcf90>

DataFrame.plot.bar會繪製多個條形圖

df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df2.plot.bar()
<matplotlib.axes._subplots.AxesSubplot at 0x1225a5d50>

繪製一個堆條形圖,傳遞參數 stack=True

df2.plot.bar(stacked=True)
<matplotlib.axes._subplots.AxesSubplot at 0x11dcf4e90>

繪製橫向條形圖,調用DataFrame.plot.barh

df2.plot.barh()
<matplotlib.axes._subplots.AxesSubplot at 0x128092410>

直方圖

df4 = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000), 'c': np.random.randn(1000) - 1}, columns=['a', 'b', 'c'])
df4.plot.hist(alpha=0.5)  # 透明度
<matplotlib.axes._subplots.AxesSubplot at 0x127f5d6d0>

堆直方圖 傳遞參數stacked=True

df4.plot.hist(stacked=True,bins=20) # bins步數
<matplotlib.axes._subplots.AxesSubplot at 0x128cb10d0>

你可以通過matplotlib的hist函數傳遞別的參數,如horizontal、cumulative

df4['a'].plot.hist(orientation='horizontal', cumulative=True)
<matplotlib.axes._subplots.AxesSubplot at 0x12a2d5950>

更多關於hist方法的使用 點擊這裏這裏

DataFrame.plot.hist和DataFrame.hist的區別

df4.hist()
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x12ac34710>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x1299cc4d0>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x129eedd50>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x129895590>]],
      dtype=object)

df4.plot.hist()
<matplotlib.axes._subplots.AxesSubplot at 0x1296508d0>

箱型圖

df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
df.plot.box()
<matplotlib.axes._subplots.AxesSubplot at 0x12a11d710>

自定義箱型圖的各個部件的顏色

color = {'boxes': 'DarkGreen', 'whiskers': 'DarkOrange', 'medians': 'DarkBlue', 'caps': 'Gray'}
df.plot.box(color=color, sym='r+')  # sym參數表示異常點的形狀
<matplotlib.axes._subplots.AxesSubplot at 0x129180dd0>

當然,你也可以傳遞matplotlib中的boxplot支持的參數,如vert=False position=[1,4,5,6,8]

df.plot.box(vert=False, positions=[1,4,6,8,15])
<matplotlib.axes._subplots.AxesSubplot at 0x12aef73d0>

DataFrame.boxplot和DataFrame.plot.box的區別 (沒啥區別,不像hist)

df.plot.box()
<matplotlib.axes._subplots.AxesSubplot at 0x12b2acdd0>

df.boxplot()
<matplotlib.axes._subplots.AxesSubplot at 0x12ae9d950>

你可以指定by參數來創建組

df = pd.DataFrame(np.random.rand(10, 2), columns=['Col1', 'Col2'])
df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'])
df.boxplot(by='X')  # 按照列X來分組繪製 兩列col1 col2的箱型圖
array([<matplotlib.axes._subplots.AxesSubplot object at 0x12a229910>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x129e54750>],
      dtype=object)

by參數支持多個列

df = pd.DataFrame(np.random.rand(10, 3), columns=['Col1', 'Col2', 'Col3'])
df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'])
df['Y'] = pd.Series(['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'])
df.boxplot(column=['Col1', 'Col2'], by=['X', 'Y'])
array([<matplotlib.axes._subplots.AxesSubplot object at 0x129f81390>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x129ef2b10>],
      dtype=object)

面積圖

df = pd.DataFrame(np.random.rand(10, 4), columns=['a','b','c','d'])
df.plot.area()
<matplotlib.axes._subplots.AxesSubplot at 0x128efdc10>

繪製一個沒有堆疊的面積圖,調用參數stacked=False

df.plot.area(stacked=False)  # 此時透明度默認值=0.5
<matplotlib.axes._subplots.AxesSubplot at 0x12fd536d0>

散點圖

df = pd.DataFrame(np.random.rand(50,4),columns=['a','b','c','d'])
df.plot.scatter(x='a', y='b')  # 散點圖必須指定參數x和y
<matplotlib.axes._subplots.AxesSubplot at 0x12fc054d0>

在同一個圖中繪製多個列的散點圖,調用參數ax

ax = df.plot.scatter(x='a',y='b',color='DarkBlue',label='Group1')
df.plot.scatter(x='c', y='d', color='DarkGreen', label='Group2', ax=ax)
<matplotlib.axes._subplots.AxesSubplot at 0x130817910>

爲每個點指定顏色,調用參數c

df.plot.scatter(x='a',y='b',c='c', s=50)  # s爲點的size
<matplotlib.axes._subplots.AxesSubplot at 0x130c95ed0>

爲每個點指定大小,調用參數s

df.plot.scatter(x='a',y='b',s=df['c']*200)
<matplotlib.axes._subplots.AxesSubplot at 0x130b2c4d0>

六邊形圖

df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])
df['b'] = df['b'] + np.arange(1000)
df.plot.hexbin(x='a', y='b', gridsize=25)
<matplotlib.axes._subplots.AxesSubplot at 0x131214cd0>

網格的size可以通過gridsize參數控制

df.plot.hexbin(x='a', y='b', gridsize=2)
<matplotlib.axes._subplots.AxesSubplot at 0x131433f90>

餅圖

series = pd.Series(3*np.random.rand(4),index=['a','b','c','d'],name='series')
series.plot.pie(figsize=(6,6))
<matplotlib.axes._subplots.AxesSubplot at 0x1358e9e90>

df = pd.DataFrame(3 * np.random.rand(4, 2), index=['a', 'b', 'c', 'd'], columns=['x', 'y'])
df.plot.pie(subplots=True, figsize=(8, 4))
array([<matplotlib.axes._subplots.AxesSubplot object at 0x12b49de10>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x1359fbf50>],
      dtype=object)

餅圖的一些常用參數:labels fontsize colors autopct figsize

series.plot.pie(labels=['AA', 'BB', 'CC', 'DD'], colors=['r', 'g', 'b', 'c'], autopct='%.2f', fontsize=20, figsize=(6,6))
<matplotlib.axes._subplots.AxesSubplot at 0x1328a35d0>

如果繪製數據之和小於1 得到的是一個扇形

pd.Series([0.1]*5).plot.pie()
<matplotlib.axes._subplots.AxesSubplot at 0x131506e50>

繪製缺失數據

繪圖類型 缺失值處理方法
線圖 在缺失處留空白
堆線圖 填充0
條形圖 填充0
散點圖 捨棄缺失值
直方圖 按列捨棄缺失值
箱型圖 按列捨棄缺失值
面積圖 填充0
KDE 按列捨棄缺失值
六邊形圖 捨棄缺失值
餅圖 填充0

幾個特殊的繪圖函數

散點圖矩陣

from pandas.plotting import scatter_matrix
df = pd.DataFrame(np.random.randn(1000, 4), columns=['a', 'b', 'c', 'd'])
scatter_matrix(df, alpha=0.2,figsize=(6,6),diagonal='kde')
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x1329fafd0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x132806ed0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x1328e1790>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x1329041d0>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x132843290>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x132918410>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x1328e6490>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x1328aa090>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x1327aea50>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x132788690>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x13283c9d0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x135ce3fd0>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x135d68cd0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x135c92990>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x135bd2390>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x1359cb090>]],
      dtype=object)

密度圖

ser = pd.Series(np.random.randn(1000))
ser.plot.kde()
<matplotlib.axes._subplots.AxesSubplot at 0x130a4a550>

安德魯斯曲線

from pandas.plotting import andrews_curves
from sklearn import datasets
data= pd.DataFrame(datasets.load_iris().data)
data.head()
0123
05.13.51.40.2
14.93.01.40.2
24.73.21.30.2
34.63.11.50.2
45.03.61.40.2
andrews_curves(data, 0)
<matplotlib.axes._subplots.AxesSubplot at 0x133a2aad0>

平行座標

from pandas.plotting import parallel_coordinates
parallel_coordinates(data, 1)
<matplotlib.axes._subplots.AxesSubplot at 0x134470ad0>

滯後圖

from pandas.plotting import lag_plot
spacing = np.linspace(-99 * np.pi, 99 * np.pi, num=1000)
data = pd.Series(0.1 * np.random.rand(1000) + 0.9 * np.sin(spacing))
lag_plot(data)
<matplotlib.axes._subplots.AxesSubplot at 0x1350ca1d0>

自相關圖

from pandas.plotting import autocorrelation_plot
spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000)
data = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing))
autocorrelation_plot(data)
<matplotlib.axes._subplots.AxesSubplot at 0x133944c10>

自舉圖

from pandas.plotting import bootstrap_plot
data = pd.Series(np.random.rand(1000))
bootstrap_plot(data)

RadViz

from pandas.plotting import radviz
data = pd.DataFrame(datasets.load_iris().data)
radviz(data, 1)
<matplotlib.axes._subplots.AxesSubplot at 0x1309befd0>

繪圖格式

詳見此處

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章