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>

绘图格式

详见此处

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值