数据可视化

对应教学日历:讲次 13


一、Matplotlib 基础

import matplotlib.pyplot as plt

常用函数

函数作用
plt.figure(figsize=(w, h))创建绘图对象
plt.plot(x, y, s)绘制折线图
plt.bar(x, y)绘制垂直条形图
plt.barh(x, y)绘制水平条形图
plt.pie(x)绘制饼图
plt.scatter(x, y)绘制散点图
plt.subplot(nrows, ncols, index)绘制子图
plt.show()显示图形
plt.title()添加标题
plt.xlabel() / plt.ylabel()添加轴名称
plt.xlim() / plt.ylim()设置轴范围
plt.xticks() / plt.yticks()设置刻度
plt.legend()显示图例

中文显示

plt.rcParams['font.sans-serif'] = ['SimHei']  # 显示中文
plt.rcParams['axes.unicode_minus'] = False    # 显示负号

plot() 参数

  • 颜色:'r'红、'g'绿、'b'蓝、'y'
  • 线型:'-'实线、'--'虚线、':'点线
  • 标记:'o'圆圈、's'方块、'^'三角形
plt.plot(x, y, 'r', label='cos(x)+1')      # 红色实线
plt.plot(x, z, 'b--', label='sin(x^2)+1')  # 蓝色虚线

二、折线图

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 1, 0.01)
y = x ** 2
plt.plot(x, y, 'b')
plt.plot(x, x ** 3)
plt.title('math example')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.ylabel('Y')
plt.legend(['y=x^2', 'y=x^3'])
plt.show()

三、条形图

import matplotlib.pyplot as plt
name = ["张三", "李四", "王五"]
score = [85, 95, 75]
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.bar(name, score)    # 垂直条形图
plt.show()
 
plt.barh(name, score)   # 水平条形图
plt.show()

四、饼图

import matplotlib.pyplot as plt
labels = ['吃饭', '日用品', '学习用具', '其它']
sizes = [1200, 300, 200, 500]
explodes = (0, 0, 0, 0.2)   # 第4块突出
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.pie(sizes, explode=explodes, labels=labels,
    autopct='%.1f%%', shadow=True)
plt.title("4月份个人消费分析")
plt.show()

五、散点图

import matplotlib.pyplot as plt
name = ["张三", "李四", "王五"]
score = [85, 95, 75]
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.scatter(name, score)
plt.show()

六、子图

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
p1 = plt.subplot(121)   # 1行2列第1个
p2 = plt.subplot(122)   # 1行2列第2个
sizes1 = [1200, 300, 200, 500]
sizes2 = [1100, 400, 300, 800]
p1.pie(sizes1)
p2.pie(sizes2)
plt.suptitle("3、4月份个人消费分析")
plt.show()

七、NumPy 基础

import numpy as np
a = np.arange(0, 10, 0.1)    # [0, 10),步长0.1
b = np.linspace(0, 10, 100)  # [0, 10],分成100份

常用函数

np.sin(x)    # 正弦
np.cos(x)    # 余弦
np.sqrt(x)   # 平方根
np.pi        # 圆周率
np.exp(x)    # 指数

作业示例

正态分布密度函数

import matplotlib.pyplot as plt
from numpy import *
plt.figure(figsize=(4, 3))
x = linspace(-5, 5, 100)
y = (1 / (sqrt(2 * pi))) * exp(-(x * x) / 2)
plt.plot(x, y, '-b')
plt.show()

参数方程绘图

from numpy import *
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 6))
plt.plot([-3, 3], [0, 0], "r")
plt.plot([0, 0], [-3, 3], "r")
t = arange(0, 2 * pi, 0.01)
x = -2 * sin(2 * t) + sin(t)
y = -2 * cos(2 * t) + cos(t)
plt.plot(x, y, 'b')
plt.show()

坐标轴+函数曲线

import matplotlib.pyplot as plt
from numpy import *
plt.figure(figsize=(6, 6))
wh = hh = 6 / 2
plt.plot([-3, 3], [0, 0], c='r')
plt.plot([0, 0], [-3, 3], c='r')
t = linspace(0, 4 * pi, 100)
x = (wh / 4) * (sin(2 * t) + 2 * cos(t))
y = (hh / 4) * (cos(2 * t) + 2 * sin(t))
plt.plot(x, y, c='b')
plt.show()

词云生成

import matplotlib.pyplot as plt
from wordcloud import WordCloud
from imageio.v2 import imread
import jieba
 
with open("二十大报告.txt", "r", encoding="utf-8") as fobj:
    txt = fobj.read()
words = jieba.lcut(txt)
pic = imread('cloud.jpg')
counts = {}
excludes = set()
with open("中文停用词.txt", "r", encoding="utf-8") as fobj:
    for i in fobj:
        i = i.strip()
        excludes.add(i)
for word in words:
    if len(word) == 1:
        continue
    elif word in excludes:
        continue
    else:
        counts[word] = counts.get(word, 0) + 1
 
wc = WordCloud(mask=pic, font_path='msyh.ttc',
    repeat=False, background_color='white',
    max_words=110, max_font_size=120,
    min_font_size=10, random_state=50, scale=10)
wc.generate_from_frequencies(counts)
plt.imshow(wc)
plt.show()

作业重点

  • plt.rcParams['font.sans-serif']=['SimHei'] 显示中文
  • plot(x, y, 'r') 绘制红色折线图
  • bar() 条形图、pie() 饼图、scatter() 散点图
  • subplot(行,列,位置) 绘制子图
  • NumPy:arange() 生成等差序列,linspace() 等分区间
  • 词云:jieba.lcut() 分词 → 字典统计 → WordCloud 生成
  • 停用词过滤:excludes 集合,len(word)==1 过滤单字