第9章 绘图和可视化

信息可视化(也叫绘图)是数据分析中最重要的⼯作之⼀。matplotlib是⼀个⽤于创建出版质量图表的桌⾯绘图包。

matplotlib⽀持各种操作系统上许多不同的GUI后端,⽽且还能将图⽚导出为各种常⻅的⽮量(vector)和光栅(raster)图:PDF、SVG、JPG、PNG、BMP、GIF等。

9.1 matplotlib API⼊⻔

如果要在Jupyter notebook或ipython使用matplotlib,需要先做出声明:(matplotlib对Jupyter notebook和ipython做了接口优化)

1
2
3
4
5
# Jupyter notebook
%matplotlib notebook

# ipython
%matplotlib

声明之后还需要导入matplotlib,matplotlib的通常引⼊约定是:

1
import matplotlib.pyplot as plt

在Jupyter notebook输入

1
2
3
4
5
6
7
8
9
%matplotlib	notebook

import numpy as np
import matplotlib.pyplot as plt


data = np.arange(10)

plt.plot(data)

1557474865190

Figure和Subplot

matplotlib的图像都位于Figure对象中
使用plt.figure创建⼀个新的Figure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure()

# 创建2*2的网格(即最多4张图),选中第一个子图
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)

# fig.add_subplot返回的对象是AxesSubplot对象
print(type(ax1))
# <class 'matplotlib.axes._subplots.AxesSubplot'>

# matplotlib就会在最后⼀个用过的subplot上进⾏绘制.
plt.plot(np.random.randn(50).cumsum(), 'k--')

# 直方图
_ = ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3)

# 散点图
ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30))

# 展示图像
plt.show()

注意:
matplotlib就会在最后⼀个⽤过的subplot上进⾏绘制.
1557537464786

matplotlib中的作图线的属性及设置方式

  • 颜色(color 简写为 c):

    1. 蓝色: ‘b’ (blue)
    2. 绿色: ‘g’ (green)
    3. 红色: ‘r’ (red)
    4. 蓝绿色(墨绿色): ‘c’ (cyan)
    5. 红紫色(洋红): ‘m’ (magenta)
    6. 黄色: ‘y’ (yellow)
    7. 黑色: ‘k’ (black)
    8. 白色: ‘w’ (white)
    9. 灰度表示: e.g. 0.75 ([0,1]内任意浮点数)
    10. RGB表示法: e.g. ‘#2F4F4F’ 或 (0.18, 0.31, 0.31)
    11. 任意合法的html中的颜色表示: e.g. ‘red’, ‘darkslategray’
  • 线型(linestyle 简写为 ls):

    1. 实线: ‘-‘
    2. 虚线: ‘–’
    3. 点画线: ‘-.’
    4. 点线: ‘:’
    5. 点: ‘.’
  • 图形标记(标记marker):

    1. 圆形: ‘o’
    2. 加号: ‘+’
    3. 叉形: ‘x’
    4. 星型: ‘*’
    5. 方形: ‘s’
  • 图像标记、线宽及透明度:

    1. 标记大小:markersize 简写为 ms
    2. 标记表面(内部)颜色:markerfacecolor 简写为 mfc
    3. 标记边缘宽度:markeredgewidth 简写为 mew
    4. 标记边缘颜色:markeredgecolor 简写为 mec
    5. 线宽:linewidth
    6. 透明度:alpha,[0,1]之间的浮点数
  • 设置线的属性的几种方式:

    1
    2
    3
    4
    5
    6
    7
    8
    # 1.直接在plt.plot()中使用'line properties'
    plt.plot(x, y, 'r--') # 颜色线型总是组合在一起

    # 2.运用关键字参数
    plt.plot(x, y, markersize=15, marker='d', markerfacecolor='g')

    # 3.混合使用1 和 2
    plt.plot(x, y, 'r--', markersize=15, marker='d', markerfacecolor='g', linewidth=2)

    注意:颜色,线型,图形标记总是组合在一起:

    1
    plt.plot(x, y, 'ro--')

上面创建子图的方法太麻烦了,可以使用plt.subplots(2, 3):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


# 创建⼀个新的Figure,并返回⼀个含有已创建的subplot对象的NumPy数组
# 创建2*3的网格
fig, axes = plt.subplots(2, 3)
print(axes)
# [[<matplotlib.axes._subplots.AxesSubplot object at 0x00000213BC9E22E8>
# <matplotlib.axes._subplots.AxesSubplot object at 0x00000213BEF5C470>
# <matplotlib.axes._subplots.AxesSubplot object at 0x00000213BEF81AC8>]
# [<matplotlib.axes._subplots.AxesSubplot object at 0x00000213BEFB4198>
# <matplotlib.axes._subplots.AxesSubplot object at 0x00000213BEFDB860>
# <matplotlib.axes._subplots.AxesSubplot object at 0x00000213BF002EB8>]]

print(fig)
# Figure(640x480)

print(type(fig))
# <class 'matplotlib.figure.Figure'>

print(type(axes))
# <class 'numpy.ndarray'>

axes[1,1].plot(np.random.randn(50).cumsum(), 'k--')

plt.show()

1557537920132

pyplot.subplots的选项:

9613137


调整subplot周围的间距

默认情况下,matplotlib会在subplot外围留下⼀定的边距,并在subplot之间留下⼀定的间距。

利⽤Figure的subplots_adjust方法修改间距:

1
2
subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None)

wspace和hspace⽤于控制宽度和高度的百分⽐,可以⽤作subplot之间的间距。

1
2
3
4
5
6
7
8
9
10
11
import numpy as np
import matplotlib.pyplot as plt


# sharex共享x轴
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
for i in range(2):
for j in range(2):
axes[i, j].hist(np.random.randn(500), bins=50, color='k', alpha=0.5)
plt.subplots_adjust(wspace=0, hspace=0)
plt.show()

1557538437511

颜⾊、标记和线型

1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np
import matplotlib.pyplot as plt


data = np.random.randn(30).cumsum()
plt.plot(data, 'r--', label='Default')
plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post')

# 图例
plt.legend(loc='best')

plt.show()

1557539262356


基础设置:

  1. 与 MATLAB 类似,使用 axis 函数指定坐标轴显示的范围:

    1
    plt.axis([xmin, xmax, ymin, ymax])
  2. 使用 plt.plot() 的返回值来设置线条属性:
    plot 函数返回一个 Line2D 对象组成的列表,每个对象代表输入的一对组合:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import numpy as np
    import matplotlib.pyplot as plt


    # 加逗号 line 中得到的是 line2D 对象,不加逗号得到的是只有一个 line2D 对象的列表
    line, = plt.plot(np.random.randn(50).cumsum(), 'r--')

    # 将抗锯齿关闭
    line.set_antialiased(False)

    plt.show()
  3. plt.setp() 修改线条性质:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    import numpy as np
    import matplotlib.pyplot as plt


    # 加逗号 line 中得到的是 line2D 对象,不加逗号得到的是只有一个 line2D 对象的列表
    lines = plt.plot(np.random.randn(50).cumsum())

    # 使用键值对
    plt.setp(lines, color='r', linewidth=2.0)

    # 或者使用 MATLAB 风格的字符串对
    plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

    plt.show()

    plt.setp(lines)的全部属性:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43

    agg_filter: unknown
    alpha: float (0.0 transparent through 1.0 opaque)
    animated: [True | False]
    antialiased or aa: [True | False]
    axes: an :class:`~matplotlib.axes.Axes` instance
    clip_box: a :class:`matplotlib.transforms.Bbox` instance
    clip_on: [True | False]
    clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ]
    color or c: any matplotlib color
    contains: a callable function
    dash_capstyle: ['butt' | 'round' | 'projecting']
    dash_joinstyle: ['miter' | 'round' | 'bevel']
    dashes: sequence of on/off ink in points
    drawstyle: ['default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post']
    figure: a :class:`matplotlib.figure.Figure` instance
    fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none']
    gid: an id string
    label: string or anything printable with '%s' conversion.
    linestyle or ls: [``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
    linewidth or lw: float value in points
    lod: [True | False]
    marker: :mod:`A valid marker style <matplotlib.markers>`
    markeredgecolor or mec: any matplotlib color
    markeredgewidth or mew: float value in points
    markerfacecolor or mfc: any matplotlib color
    markerfacecoloralt or mfcalt: any matplotlib color
    markersize or ms: float
    markevery: [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
    path_effects: unknown
    picker: float distance in points or callable pick function ``fn(artist, event)``
    pickradius: float distance in points
    rasterized: [True | False | None]
    sketch_params: unknown
    snap: unknown
    solid_capstyle: ['butt' | 'round' | 'projecting']
    solid_joinstyle: ['miter' | 'round' | 'bevel']
    transform: a :class:`matplotlib.transforms.Transform` instance
    url: a url string
    visible: [True | False]
    xdata: 1D array
    ydata: 1D array
    zorder: any number
  4. 图形上加上文字:

    • xlabel :x 轴标注
    • ylabel :y 轴标注
    • title :图形标题
    • text :在指定位置放入文字
    • annotate:注释
      1. xy参数 :注释位置
      2. xytext参数 :注释文字位置
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    import numpy as np
    import matplotlib.pyplot as plt


    mu, sigma = 100, 15
    x = mu + sigma * np.random.randn(10000)

    # the histogram of the data
    n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)

    # x轴标签名
    plt.xlabel('Smarts')
    plt.ylabel('Probability')

    # 图形标题
    plt.title('Histogram of IQ')

    # 在指定位置放入文字
    # 如果要输入特殊符号,需要使用Tex语法
    plt.text(60, .025, r'$\mu=100,\ \sigma=15$')

    plt.axis([40, 160, 0, 0.03])

    # 是否显示网格
    plt.grid(True)

    plt.show()

    1557541333930

刻度、标签和图例

对于⼤多数的图表装饰项,其主要实现⽅式有⼆:

  • 使⽤过程型的pyplot接⼝(例如,matplotlib.pyplot)
  • 更为⾯向对象的原生matplotlib API。

pyplot接口的设计⽬的就是交互式使⽤:

  • xlim⽅法:
    控制图表的范围
  • xticks⽅法:
    控制刻度位置
  • xticklabels⽅法:
    控制刻度标签

使⽤⽅式:

  • 调⽤时不带参数,则返回当前的参数值
    (例如,plt.xlim()返回当前的X轴绘图范围)。
  • 调⽤时带参数,则设置参数值
    (例如,plt.xlim([0,10])会将X轴的范围设置为0到10)。

所有这些⽅法都是AxesSubplot起作⽤的。
它们各⾃对应subplot对象上的两个⽅法,以xlim为例,就是ax.get_xlimax.set_xlim

设置标题、轴标签、刻度以及刻度标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.random.randn(1000).cumsum())

# 设置轴标签范围
ticks = ax.set_xticks([0, 250, 500, 750, 1000])

# 设置标签值,倾斜30度小字体
labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],
rotation=30, fontsize='small')

# 设置图形名称
ax.set_title('My first matplotlib plot')

# 设置轴名称
ax.set_xlabel('Stages')

plt.show()

1557543158160

要是嫌上面的代码太繁琐,可以直接使用set函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

ax.plot(np.random.randn(1000).cumsum())

props = {
'title': 'My first matplotlib plot',
'xlabel': 'Stages',
'xticklabels':['one', 'two', 'three', 'four', 'five'],
'xticks':[0, 250, 500, 750, 1000],
}
ax.set(**props)


plt.show()

添加图例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import randn


# fig, axes = plt.subplots(1, 1)
ax = plt.subplots(1, 1)[-1]

# 在添加subplot的时候传⼊label参数:
ax.plot(randn(1000).cumsum(), 'r', label='one')
ax.plot(randn(1000).cumsum(), 'g--', label='two')
ax.plot(randn(1000).cumsum(), 'b.', label='three')


# ax.legend()来⾃动创建图例
# loc告诉matplotlib要将图例放在哪
ax.legend(loc='best')

plt.show()

Figure_1

注解以及在Subplot上绘图

注解和⽂字可以通过text、arrow和annotate函数进⾏添加。text可以将⽂本绘制在图表的指定坐标(x,y),还可以加上⼀些⾃定义格式:

1
ax.text(x, y, 'Hello world!',family='monospace', fontsize=10)

ax.annotate⽅法:在指定的x和y坐标轴绘制标签。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from datetime import datetime

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


fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

data = pd.read_csv('examples/spx.csv', index_col=0, parse_dates=True)
spx = data['SPX']


spx.plot(ax=ax, style='r-')


crisis_data = [
(datetime(2007, 10, 11), 'Peak of bull market'),
(datetime(2008, 3, 12), 'Bear Stearns Fails'),
(datetime(2008, 9, 15), 'Lehman Bankruptcy')
]

for date, label in crisis_data:
ax.annotate(label, xy=(date, spx.asof(date) + 75),
xytext=(date, spx.asof(date) + 225),
arrowprops=dict(facecolor='black', headwidth=4, width=2,headlength=4),
horizontalalignment='left', verticalalignment='top')

# Zoom in on 2007-2010
ax.set_xlim(['1/1/2007', '1/1/2011'])
ax.set_ylim([600, 1800])

ax.set_title('Important dates in the 2008-2009 financial crisis')

plt.show()

Figure_2

图形的绘制要麻烦⼀些。
matplotlib有⼀些表示常⻅图形的对象。这些对象被称为(patch)。
要在图表中添加⼀个图形,你需要创建⼀个块对象shp,然后通过ax.add_patch(shp)将其添加到subplot中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)


# 创建⼀个块对象shp
# 三角形
rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3)
# 圆形
circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)
# 多边形
pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],color='g', alpha=0.5)

# ax.add_patch(shp)将shp对象添加到subplot中:
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)

plt.show()

Figure_3

将图表保存到⽂件

  • plt.savefig:将当前图表保存到⽂件。

    1
    2
    3
    # dpi:“每英⼨点数”分辨率
    # bbox_inches:剪除当前图表周围的空⽩部分
    plt.savefig('figpath.png', dpi=400, bbox_inches='tight')
  • Figure对象的实例⽅法savefig

savefig并⾮⼀定要写⼊磁盘,也可以写⼊任何⽂件型的对象,⽐如BytesIO:

1
2
3
4
5
![36985537](F:/乱七八糟/360安全浏览器下载/chrome/下载/36985537.pngfrom io import BytesIO

buffer = BytesIO()
plt.savefig(buffer)
plot_data = buffer.getvalue()

Figure.savefig选项

36985537

matplotlib配置

rc⽅法

  • 第⼀个参数是希望⾃定义的对象,’figure’、’axes’、’xtick’、’ytick’、’grid’、’legend’等。
  • 后面都是关键字参数.
    所以可以使用字典传入
1
2
3
4
5
6
7
8
9
# 将全局的图像默认⼤⼩设置为10×10,你可以执⾏
plt.rc('figure', figsize=(10, 10))


# 使用字典传入
font_options = {'family' : 'monospace',
'weight' : 'bold',
'size' : 'small'}
plt.rc('font', **font_options)

9.2 使⽤pandas和seaborn绘图

图表的基本组件:

  • 数据展示:
    图表类型:线型图、柱状图、盒形图、散布图、等值线图等
  • 图例
  • 标题
  • 刻度标
  • 注解型信息。

线型图:
默认创建的图形就是线性图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


s = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))
print(s)
# 0 -0.166507
# 10 -1.134936
# 20 -0.253578
# 30 -1.814358
# 40 -3.598128
# 50 -3.102310
# 60 -3.294786
# 70 -3.554902
# 80 -3.329025
# 90 -4.211883
# dtype: float64

s.plot()

1557547900645

  • ==该Series对象的索引会被传给matplotlib,并⽤以绘制X轴。==可以通过use_index=False禁⽤该功能。
  • X轴的刻度和界限通过xticks和xlim选项进⾏调节,Y轴就⽤yticks和ylim。

plot参数的完整列表:

参数 说明
label 图例标签
ax 要在其上进行绘制的 matplotlib subplot对象。如果没有设置,则使用当前matplotlib subplot
style 将要传给 matplotlib的风格字符串(如’ko–’)
alpha 图表的填充不透明度(0到1之间)
kind 可以是’line’、’bar‘、’barh、’kde’
logy 在Y轴上使用对数标尺
use_index 将对象的索引用作刻度标签
rot 旋转刻度标签(0到360)
xticks 用作X轴刻度的值
yticks 用作Y轴刻度的值
xlim X轴的界限(例如[0,10])
ylim Y轴的界限
grid 显示轴网格线(默认打开)

注意:
plot的关键字参数会被传给相应的matplotlib绘图函数,所以要更深⼊地⾃定义图表,就必须学习有关matplotlib API。

DataFrame的plot⽅法会在⼀个subplot中为各列绘制⼀条线,并⾃动创建图例
也就是说,==一个series就绘制一条线==

1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np
import matplotlib.pyplot as plt


np.random.seed(888)

df = pd.DataFrame(np.random.randn(10, 4).cumsum(0),
columns=['A', 'B', 'C', 'D'],
index=np.arange(0, 100, 10))

df.plot()
plt.show()

Figure_4

专⽤于DataFrame的plot参数

7777777537

柱状图

plot.bar()和plot.barh()分别绘制⽔平和垂直的柱状图.
这时,Series和DataFrame的索引将会被⽤作X(bar)或Y(barh)刻度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


np.random.seed(888)

fig, axes = plt.subplots(2, 1)

data = pd.Series(np.random.rand(16), index=list('abcdefghijklmnop'))

# 将行索引作为刻度
data.plot.bar(ax=axes[0], color='k', alpha=0.7)
data.plot.barh(ax=axes[1], color='k', alpha=0.7)


plt.show()

Figure_5

对于DataFrame,

  • 柱状图会将每⼀列的值分为⼀组,并排显示
  • DataFrame各列的名称”Genus”被⽤作了图例的标题
  • 设置stacked=True即可为DataFrame⽣成堆积柱状图
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


np.random.seed(12348)
fig, axes = plt.subplots(1, 1)

df = pd.DataFrame(np.random.rand(6, 4),
index=['one', 'two', 'three', 'four', 'five', 'six'],
columns=pd.Index(['A', 'B', 'C', 'D'], name='Genus'))

df.plot.bar()

plt.show()

Figure_6

柱状图有⼀个⾮常不错的⽤法:利⽤value_counts图形化显示Series中各值的出现频率:

1
2
3
4
5
6
7
8
9
10
![Figure_8](C:/Users/lenovo/Figure_8.pngimport numpy as np
import pandas as pd
import matplotlib.pyplot as plt

np.random.seed(1238)
se = pd.Series(np.random.randint(1,5,10), name='Genus')

se.value_counts().plot.bar(title='frequency')

plt.show()

Figure_8

将柱状图堆积:
df.plot.barh(stacked=True, alpha=0.5)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


np.random.seed(12348)

fig, axes = plt.subplots(1, 1)

df = pd.DataFrame(np.random.rand(6, 4),
index=['one', 'two', 'three', 'four', 'five', 'six'],
columns=pd.Index(['A', 'B', 'C', 'D'], name='Genus'))

df.plot.barh(stacked=True, alpha=0.5)


plt.show()

Figure_7

做⼀张堆积柱状图以展示每天各种聚会规模的数据点的百分⽐。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


tips = pd.read_csv('examples/tips.csv')
party_counts = pd.crosstab(tips['day'], tips['size'])
print(party_counts)
# size 1 2 3 4 5 6
# day
# Fri 1 16 1 1 0 0
# Sat 2 53 18 13 1 0
# Sun 0 39 15 18 3 1
# Thur 1 48 4 5 1 3

# 获取2行到5行
party_counts = party_counts.loc[:, 2:5]

# 除以总人数得到比例
party_pcts = party_counts.div(party_counts.sum(1), axis=0)
print(party_pcts)
# size 2 3 4 5
# day
# Fri 0.888889 0.055556 0.055556 0.000000
# Sat 0.623529 0.211765 0.152941 0.011765
# Sun 0.520000 0.200000 0.240000 0.040000
# Thur 0.827586 0.068966 0.086207 0.017241

party_pcts.plot.bar()
plt.show()

Figure_9

直⽅图和密度图

直⽅图:histogram.所以函数为hist

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


df = pd.DataFrame({
'length': [1.5, 0.5, 1.2, 0.9, 3],
'width': [0.7, 0.2, 0.15, 0.2, 1.1]},
index= ['pig', 'rabbit', 'duck', 'chicken', 'horse'])

# 显示在3个bins中
hist = df.hist(bins=3)

plt.show()

Figure_10

密度图也被称作KDE(Kernel Density Estimate,核密度估计)图。
所以密度图的函数就是density()

1
2
3
4
5
6
7
8
9
10
11
12
13
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


df = pd.DataFrame({
'length': [1.5, 0.5, 1.2, 0.9, 3],
'width': [0.7, 0.2, 0.15, 0.2, 1.1]},
index= ['pig', 'rabbit', 'duck', 'chicken', 'horse'])

hist = df.plot.density()

plt.show()

Figure_11

seaborn的distplot⽅法绘制直⽅图和密度图更加简单,还可以同时画出直⽅图和连续密度估计图。

实现⼀个双峰分布,由两个不同的标准正态分布组成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

np.random.seed(12348)

comp1 = np.random.normal(0, 1, size=200)
comp2 = np.random.normal(10, 2, size=200)
values = pd.Series(np.concatenate([comp1, comp2]))
print(values)

sns.distplot(values, bins=100, color='k')
# 0 1.309562
# 1 -1.647653
# 2 -0.076477
# ...
# 397 12.130122
# 398 10.297347
# 399 8.813654
# Length: 400, dtype: float64

plt.show()

Figure_12

散布图或点图
使⽤seaborn的regplot⽅法,它可以做⼀个散布图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

macro = pd.read_csv('examples/macrodata.csv')
data = macro[['cpi', 'm1', 'tbilrate', 'unemp']]
trans_data = np.log(data).diff().dropna()

print(trans_data[-5:])
# cpi m1 tbilrate unemp
# 198 -0.007904 0.045361 -0.396881 0.105361
# 199 -0.021979 0.066753 -2.277267 0.139762
# 200 0.002340 0.010286 0.606136 0.160343
# 201 0.008419 0.037461 -0.200671 0.127339
# 202 0.008894 0.012202 -0.405465 0.042560


sns.regplot('m1', 'unemp', data=trans_data)
plt.title('Changes in log %s versus log %s' % ('m1', 'unemp'))

plt.show()

Figure_13

在探索式数据分析⼯作中,同时观察⼀组变量的散布图是很有意义的,这也被称为散布图矩阵(scatter plot matrix)。
这是要使用seaborn库的pairplot:
它⽀持在对⻆线上放置每个变量的直⽅图或密度估计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

macro = pd.read_csv('examples/macrodata.csv')
data = macro[['cpi', 'm1', 'tbilrate', 'unemp']]
trans_data = np.log(data).diff().dropna()

print(trans_data[-5:])
# cpi m1 tbilrate unemp
# 198 -0.007904 0.045361 -0.396881 0.105361
# 199 -0.021979 0.066753 -2.277267 0.139762
# 200 0.002340 0.010286 0.606136 0.160343
# 201 0.008419 0.037461 -0.200671 0.127339
# 202 0.008894 0.012202 -0.405465 0.042560

sns.pairplot(trans_data, diag_kind='kde', plot_kws={'alpha': 0.2})

plt.show()

Figure_14

分⾯⽹格(facet grid)和类型数据

有多个分类变量的数据可视化的⼀种⽅法是使⽤⼩⾯⽹格。seaborn有⼀个有⽤的内置函数factorplot,可以简化制作多种分⾯图

看不懂,略