Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
 知乎专栏 ｜ 多维度架构

## 12.5. 数据可视化

1. 数据准备：从数据库,Excle,CSV文件，HTML表格等等
3. 数据清洗：删除，排序，筛选，分组聚合，运算
4. 数据可视化：使用 matplotlib 生成图表

### 12.5.1. 演示代码

#### 12.5.1.1. 折线图

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

df = pd.DataFrame(np.random.randn(15, 4), index=pd.date_range(
'2021/01/01', periods=15), columns=list('ABCD'))

df.plot()
plt.show()

```

#### 12.5.1.2. 条形图

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

df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])
df.plot.bar()
plt.show()

```
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])
df.plot.bar(stacked=True)
plt.show()

```
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])

df.plot.barh(stacked=True)
plt.show()

```

#### 12.5.1.3. 直方图

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

df = pd.DataFrame({'A': np.random.randn(1000)-1,
'B': np.random.randn(1000),
'C': np.random.randn(1000)+1},
columns=['A', 'B', 'C'])

df.plot.hist(bins=20)
plt.show()

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

data = np.random.randn(1000)

df = pd.DataFrame({'A': data, 'B': data, 'C': data}, columns=['A', 'B', 'C'])

df.hist(bins=20)
plt.show()

```

#### 12.5.1.4. 区域图

```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])
df.plot.area()
plt.show()

```

#### 12.5.1.5. 饼形图

```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(5),
index=['A', 'B', 'C', 'D', 'E'], columns=['Pie'])
df.plot.pie(subplots=True)
plt.show()

```

#### 12.5.1.6. XY散点图

```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(50, 4), columns=['A', 'B', 'C', 'D'])
df.plot.scatter(x='A', y='B')
plt.show()

```

#### 12.5.1.7. 箱形图

```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
df.plot.box()
plt.show()

```

#### 12.5.1.8. 核密度估计图（Kernel Density Estimation, KDE）

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

df = pd.Series(np.random.normal(loc=0, scale=5, size=10000))
df.plot(kind='kde')
df.hist(density=True)
plt.grid()
plt.show()

```

### 12.5.2. 中文支持

#### 12.5.2.1. 查看系统支持的字体

```
from matplotlib import font_manager
a = sorted([f.name for f in font_manager.fontManager.ttflist])
for i in a:
print(i)

```

```
.Aqua Kana
.Arabic UI Display
.Arabic UI Text
.Keyboard
.New York
.New York
.SF Compact
.SF Compact
.SF Compact Rounded
.SF NS Mono
.SF NS Mono
.SF NS Rounded
Al Bayan
Al Nile
Al Tarikh
American Typewriter
Andale Mono
Apple Braille
Apple Braille
Apple Braille
Apple Braille
Apple Braille
Apple Chancery
Apple SD Gothic Neo
Apple Symbols
AppleGothic
AppleMyungjo
Arial
Arial
Arial
Arial
Arial Black
Arial Hebrew
Arial Narrow
Arial Narrow
Arial Narrow
Arial Narrow
Arial Rounded MT Bold
Arial Unicode MS
Arial Unicode MS
Athelas
Avenir
Avenir Next
Avenir Next Condensed
Ayuthaya
Bangla MN
Bangla Sangam MN
Beirut
Big Caslon
Birch Std
Blackoak Std
Bodoni 72
Bodoni 72 Oldstyle
Bodoni 72 Smallcaps
Bodoni Ornaments
Brush Script MT
Brush Script Std
Chalkboard
Chalkboard SE
Chalkduster
Chaparral Pro
Chaparral Pro
Chaparral Pro
Chaparral Pro
Chaparral Pro
Charlemagne Std
Charter
Cochin
Comic Sans MS
Comic Sans MS
Cooper Std
Cooper Std
Copperplate
Corsiva Hebrew
Courier New
Courier New
Courier New
Courier New
DIN Alternate
DIN Condensed
Damascus
DejaVu Sans
DejaVu Sans
DejaVu Sans
DejaVu Sans
DejaVu Sans Display
DejaVu Sans Mono
DejaVu Sans Mono
DejaVu Sans Mono
DejaVu Sans Mono
DejaVu Serif
DejaVu Serif
DejaVu Serif
DejaVu Serif
DejaVu Serif Display
Devanagari MT
Devanagari Sangam MN
Didot
Diwan Kufi
Diwan Thuluth
Euphemia UCAS
Farah
Farisi
Futura
Galvji
Geeza Pro
Georgia
Georgia
Georgia
Georgia
Giddyup Std
Gill Sans
Gujarati MT
Gujarati Sangam MN
Gurmukhi MN
Gurmukhi MT
Gurmukhi Sangam MN
Heiti TC
Heiti TC
Helvetica
Helvetica Neue
Herculanum
Hiragino Maru Gothic Pro
Hiragino Mincho ProN
Hiragino Sans
Hiragino Sans
Hiragino Sans
Hiragino Sans
Hiragino Sans
Hiragino Sans
Hiragino Sans
Hiragino Sans
Hiragino Sans
Hiragino Sans
Hiragino Sans GB
Hobo Std
Hoefler Text
Hoefler Text
ITF Devanagari
Impact
InaiMathi
Iowan Old Style
Kailasa
Kefa
Khmer MN
Khmer Sangam MN
Kohinoor Bangla
Kohinoor Devanagari
Kohinoor Gujarati
Kohinoor Telugu
Kokonor
Kozuka Gothic Pr6N
Kozuka Gothic Pr6N
Kozuka Gothic Pr6N
Kozuka Gothic Pr6N
Kozuka Gothic Pr6N
Kozuka Gothic Pr6N
Kozuka Gothic Pro
Kozuka Gothic Pro
Kozuka Gothic Pro
Kozuka Gothic Pro
Kozuka Gothic Pro
Kozuka Gothic Pro
Kozuka Mincho Pr6N
Kozuka Mincho Pr6N
Kozuka Mincho Pr6N
Kozuka Mincho Pr6N
Kozuka Mincho Pr6N
Kozuka Mincho Pr6N
Kozuka Mincho Pro
Kozuka Mincho Pro
Kozuka Mincho Pro
Kozuka Mincho Pro
Kozuka Mincho Pro
Kozuka Mincho Pro
Krungthep
KufiStandardGK
Lao MN
Lao Sangam MN
Letter Gothic Std
Letter Gothic Std
Letter Gothic Std
Letter Gothic Std
Lithos Pro
Lithos Pro
Lucida Grande
Luminari
Malayalam MN
Malayalam Sangam MN
Marion
Marker Felt
Menlo
Mesquite Std
Microsoft Sans Serif
Minion Pro
Minion Pro
Minion Pro
Minion Pro
Minion Pro
Minion Pro
Minion Pro
Minion Pro
Minion Pro
Minion Pro
Mishafi
Mishafi Gold
Mshtakan
Mukta Mahee
Muna
Myanmar MN
Myanmar Sangam MN
New Peninim MT
Noteworthy
Noto Nastaliq Urdu
Noto Sans Armenian
Noto Sans Avestan
Noto Sans Bamum
Noto Sans Bassa Vah
Noto Sans Batak
Noto Sans Bhaiksuki
Noto Sans Brahmi
Noto Sans Buginese
Noto Sans Buhid
Noto Sans Carian
Noto Sans Caucasian Albanian
Noto Sans Chakma
Noto Sans Cham
Noto Sans Coptic
Noto Sans Cuneiform
Noto Sans Cypriot
Noto Sans Duployan
Noto Sans Egyptian Hieroglyphs
Noto Sans Elbasan
Noto Sans Glagolitic
Noto Sans Gothic
Noto Sans Hanifi Rohingya
Noto Sans Hanunoo
Noto Sans Hatran
Noto Sans Imperial Aramaic
Noto Sans Inscriptional Pahlavi
Noto Sans Inscriptional Parthian
Noto Sans Javanese
Noto Sans Kaithi
Noto Sans Kayah Li
Noto Sans Kharoshthi
Noto Sans Khojki
Noto Sans Lepcha
Noto Sans Limbu
Noto Sans Linear A
Noto Sans Linear B
Noto Sans Lisu
Noto Sans Lycian
Noto Sans Lydian
Noto Sans Mahajani
Noto Sans Mandaic
Noto Sans Manichaean
Noto Sans Marchen
Noto Sans Meetei Mayek
Noto Sans Mende Kikakui
Noto Sans Meroitic
Noto Sans Miao
Noto Sans Modi
Noto Sans Mongolian
Noto Sans Mro
Noto Sans Multani
Noto Sans Myanmar
Noto Sans NKo
Noto Sans Nabataean
Noto Sans New Tai Lue
Noto Sans Newa
Noto Sans Ogham
Noto Sans Ol Chiki
Noto Sans Old Hungarian
Noto Sans Old Italic
Noto Sans Old North Arabian
Noto Sans Old Permic
Noto Sans Old Persian
Noto Sans Old South Arabian
Noto Sans Old Turkic
Noto Sans Oriya
Noto Sans Osage
Noto Sans Osmanya
Noto Sans Pahawh Hmong
Noto Sans Palmyrene
Noto Sans Pau Cin Hau
Noto Sans PhagsPa
Noto Sans Phoenician
Noto Sans Psalter Pahlavi
Noto Sans Rejang
Noto Sans Runic
Noto Sans Samaritan
Noto Sans Saurashtra
Noto Sans Shavian
Noto Sans Siddham
Noto Sans Sora Sompeng
Noto Sans Sundanese
Noto Sans Syloti Nagri
Noto Sans Syriac
Noto Sans Tagalog
Noto Sans Tagbanwa
Noto Sans Tai Le
Noto Sans Tai Tham
Noto Sans Tai Viet
Noto Sans Takri
Noto Sans Thaana
Noto Sans Tifinagh
Noto Sans Tirhuta
Noto Sans Ugaritic
Noto Sans Vai
Noto Sans Wancho
Noto Sans Warang Citi
Noto Sans Yi
Noto Serif Ahom
Noto Serif Balinese
Noto Serif Myanmar
Nueva Std
Nueva Std
Nueva Std
Nueva Std
Nueva Std
Nueva Std
OCR A Std
Optima
Orator Std
Orator Std
Oriya MN
Oriya Sangam MN
PT Mono
PT Sans
PT Serif
PT Serif Caption
Palatino
Papyrus
Party LET
Phosphate
PingFang HK
Plantagenet Cherokee
Poplar Std
Prestige Elite Std
Raanana
Rockwell
Rosewood Std
SF Compact
SF Compact
SF Compact Display
SF Compact Display
SF Compact Display
SF Compact Display
SF Compact Display
SF Compact Display
SF Compact Display
SF Compact Display
SF Compact Display
SF Compact Rounded
SF Compact Rounded
SF Compact Rounded
SF Compact Rounded
SF Compact Rounded
SF Compact Rounded
SF Compact Rounded
SF Compact Rounded
SF Compact Rounded
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Compact Text
SF Pro
SF Pro
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Display
SF Pro Rounded
SF Pro Rounded
SF Pro Rounded
SF Pro Rounded
SF Pro Rounded
SF Pro Rounded
SF Pro Rounded
SF Pro Rounded
SF Pro Rounded
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
SF Pro Text
STHeiti
STIXGeneral
STIXGeneral
STIXGeneral
STIXGeneral
STIXGeneral
STIXGeneral
STIXGeneral
STIXGeneral
STIXIntegralsD
STIXIntegralsD
STIXIntegralsSm
STIXIntegralsSm
STIXIntegralsUp
STIXIntegralsUp
STIXIntegralsUpD
STIXIntegralsUpD
STIXIntegralsUpSm
STIXIntegralsUpSm
STIXNonUnicode
STIXNonUnicode
STIXNonUnicode
STIXNonUnicode
STIXNonUnicode
STIXNonUnicode
STIXNonUnicode
STIXNonUnicode
STIXSizeFiveSym
STIXSizeFiveSym
STIXSizeFourSym
STIXSizeFourSym
STIXSizeFourSym
STIXSizeFourSym
STIXSizeOneSym
STIXSizeOneSym
STIXSizeOneSym
STIXSizeOneSym
STIXSizeThreeSym
STIXSizeThreeSym
STIXSizeThreeSym
STIXSizeThreeSym
STIXSizeTwoSym
STIXSizeTwoSym
STIXSizeTwoSym
STIXSizeTwoSym
STIXVariants
STIXVariants
Sana
Sathu
Savoye LET
Seravek
Shree Devanagari 714
SignPainter
Silom
Sinhala MN
Sinhala Sangam MN
Skia
Snell Roundhand
Songti SC
Source Code Pro
Source Code Pro
Source Code Pro
Source Code Pro
Source Code Pro
Source Code Pro
Stencil Std
Sukhumvit Set
Superclarendon
Symbol
System Font
System Font
Tahoma
Tahoma
Tamil MN
Tamil Sangam MN
Tekton Pro
Tekton Pro
Tekton Pro
Tekton Pro
Telugu MN
Telugu Sangam MN
Thonburi
Times
Times New Roman
Times New Roman
Times New Roman
Times New Roman
Trajan Pro
Trajan Pro
Trattatello
Trebuchet MS
Trebuchet MS
Trebuchet MS
Trebuchet MS
Verdana
Verdana
Verdana
Verdana
Waseem
Webdings
Wingdings
Wingdings 2
Wingdings 3
Zapf Dingbats
Zapfino
cmb10
cmex10
cmmi10
cmr10
cmss10
cmsy10
cmtt10

```

#### 12.5.2.2. 设置字体

```
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['PingFang HK']
mpl.rcParams['font.serif'] = ['PingFang HK']
plt.rcParams['axes.unicode_minus'] = False

```

#### 12.5.2.3. 中文演示代码

```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['PingFang HK']
mpl.rcParams['font.serif'] = ['PingFang HK']
plt.rcParams['axes.unicode_minus'] = False

df = sheet[2:-3]
print(df)
df.plot.line(x='客户名', y='合计')
plt.show()

```

### 12.5.3. 开启网格

plt.grid()

```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['PingFang HK']
mpl.rcParams['font.serif'] = ['PingFang HK']
plt.rcParams['axes.unicode_minus'] = False

df = sheet[2:-3]
# print(df)
df.plot.line(x='客户名', y='合计')
plt.title('销售业绩表')
plt.xlabel('客户')
plt.ylabel('消费金额')
plt.grid()
plt.show()

```

### 12.5.4. 坐标轴

xlabel():设置x坐标轴名称
ylabel():设置y坐标轴名称
xlim(): 设置x坐标轴范围
ylim(): 设置y坐标轴范围
xticks():设置x轴刻度
yticks():设置y轴刻度

#### 12.5.4.1. 轴标签旋转

```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['PingFang HK']
mpl.rcParams['font.serif'] = ['PingFang HK']
plt.rcParams['axes.unicode_minus'] = False

df = sheet[2:-3]
print(df)
df.plot.line(x='客户名', y='合计')
plt.xticks(rotation=90)  # X 轴标签旋转90度
plt.show()

```

#### 12.5.4.2.

```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['PingFang HK']
mpl.rcParams['font.serif'] = ['PingFang HK']
plt.rcParams['axes.unicode_minus'] = False

data = {'序号': list(range(6)),
'姓名': ['张三', '李四', '王五', '赵六', '牛七', '马八'],
'年龄': [23, 25, 26, 25, 25, 27],
'生日': ['2001-12-01', '2001-12-05', '2001-10-01', '2001-1-5', '2002-2-15', '2001-08-01'],
'数学': [88, 85, 60, 56, 90, 100],
'语文': [78, 75, 80, 67, 92, 96]
}

df = pd.DataFrame(data)

df.plot.line(x='姓名', y=['数学', '语文'])
plt.xticks(rotation=30)
plt.yticks([60, 80, 90, 100], ['及格', '良好',
'优秀', '满分'])
plt.grid()
plt.show()

```

#### 12.5.4.3. 标题/X标签/Y标签

```
plt.title('销售业绩表')
plt.xlabel('客户')
plt.ylabel('消费金额')

```

#### 12.5.4.4. 设置X/Y坐标范围

```
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')

plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.show()

```

### 12.5.5. 边框设置

```
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

```

```
#! /usr/bin/env python
# coding=utf-8
import matplotlib.pyplot as plt
import numpy as np
import math
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['PingFang HK']
mpl.rcParams['font.serif'] = ['PingFang HK']
plt.rcParams['axes.unicode_minus'] = False

x = np.arange(0, math.pi*2, 0.05)
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])  # main axes
y = np.sin(x)
ax.plot(x, y)
ax.set_title('正弦')
ax.set_yticks([-1, 0, 1])

ax = plt.gca()
# 设置上边和右边无边框
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 设置x坐标的位置
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

plt.show()

```

### 12.5.6. plot 设置

df.plot 参数

df.plot(x, y, kind, figsize, title, grid, legend, style)

x  x 横坐标变量
y  Y 纵坐标变量
kind  可视化图的种类，如line,hist, bar, barh, pie, kde, scatter
figsize 画布尺寸
title  标题
grid  是否显示格子线条
legend  是否显示图例
style  图的风格

#### 12.5.6.1.

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

mpl.rcParams['font.sans-serif'] = ['PingFang HK']
mpl.rcParams['font.serif'] = ['PingFang HK']
plt.rcParams['axes.unicode_minus'] = False

data = {'序号': list(range(6)),
'姓名': ['张三', '李四', '王五', '赵六', '牛七', '马八'],
'语文': [78, 75, 80, 67, 92, 96],
'数学': [88, 85, 60, 56, 90, 100],
'英语': [75, 50, 69, 98, 82, 79],
'历史': [72, 87, 65, 99, 72, 89]
}

df = pd.DataFrame(data)
print(df)
df.plot.line(x='姓名', y=['语文', '数学', '英语', '历史'],  # 4个变量可视化
legend=True,  # 显示图例
subplots=True,  # 多子图并存
layout=(2, 2),  # 图形排列2行2列
figsize=(20, 10),  # 图形尺寸
title='成绩单'  # 标题
)

plt.show()

```

#### 12.5.6.2. 隐藏图例

legend=False

```

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

mpl.rcParams['font.sans-serif'] = ['PingFang HK']
mpl.rcParams['font.serif'] = ['PingFang HK']
plt.rcParams['axes.unicode_minus'] = False

data = {'序号': list(range(6)),
'姓名': ['张三', '李四', '王五', '赵六', '牛七', '马八'],
'年龄': [23, 25, 26, 25, 25, 27],
'生日': ['2001-12-01', '2001-12-05', '2001-10-01', '2001-1-5', '2001-2-15', '2001-08-01'],
'数学': [88, 85, 60, 56, 90, 100],
'语文': [78, 75, 80, 67, 92, 96]
}

df = pd.DataFrame(data)
df.生日 = pd.to_datetime(df.生日)
df.plot.line(x='姓名', y='生日', legend=False)
plt.grid()
plt.show()

```

### 12.5.7. 保存为图片

```
plt.savefig('1.svg')

plt.savefig('2.png',dpi=400,bbox_inches='tight')

```

### 12.5.8. matplotlib 绘图风格

```
import matplotlib.pyplot as plt
print(plt.style.available)

```

```
['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']

```

```
plt.style.use('ggplot')

```