Day 8 数据可视化 - 考前冲刺课件
🎯 考试重点速记(90分保障)
一、核心知识框架
1. Matplotlib基础(必考⭐⭐⭐)
python
import matplotlib.pyplot as plt
# 三大核心步骤
# 1. 创建绘图区
fig, ax = plt.subplots(figsize=(6,4))
# 2. 绘制图表
plt.plot(x, y)
# 3. 显示图表
plt.show()
中文显示问题(必考):
python
plt.rcParams['font.sans-serif'] = ['SimHei'] # 黑体
plt.rcParams['axes.unicode_minus'] = False # 显示负号
2. 七大图表类型(重点)
| 图表类型 | 函数 | 应用场景 |
|---|---|---|
| 折线图 | plt.plot(x,y) |
趋势变化 |
| 柱状图 | plt.bar(x,height,width) |
分类对比 |
| 饼图 | plt.pie(data,labels) |
占比关系 |
| 散点图 | plt.scatter(x,y) |
相关性分析 |
| 直方图 | plt.hist(x,bins) |
数据分布 |
| 箱形图 | plt.boxplot(data) |
统计分析 |
| 3D图 | ax.plot_surface(X,Y,Z) |
三维展示 |
二、必考知识点
📌 知识点1:绘图区设置
python
# 方法1:自动创建(默认6.4*4.8英寸)
plt.plot([1,2,3])
# 方法2:手动创建(推荐)
fig, ax = plt.subplots(figsize=(6,4), dpi=100)
# 子图创建
plt.subplot(2,3,1) # 2行3列第1个
# 或简写
plt.subplot(231)
考点: subplot(nrows, ncols, index)
📌 知识点2:坐标轴设置
python
# 标题和标签
plt.title("标题")
plt.xlabel("X轴")
plt.ylabel("Y轴")
# 刻度范围
plt.xlim(0, 10)
plt.ylim(-1, 1)
# 自定义刻度
plt.xticks([0,1,2,3], ['春','夏','秋','冬'])
# 网格线
plt.grid(axis='y') # 只显示横向网格
📌 知识点3:折线图(⭐⭐⭐必考)
python
# 完整格式
plt.plot(x, y, 'ro-', linewidth=2, label='数据')
# 格式字符串:颜色+标记+线型
# 'r' - 红色, 'o' - 圆圈, '-' - 实线
常用参数表:
| 颜色 | 标记 | 线型 |
|---|---|---|
| r-红 | o-圆 | - 实线 |
| g-绿 | *-星 | -- 虚线 |
| b-蓝 | ^-三角 | : 点线 |
| y-黄 | D-菱形 | -. 点划线 |
典型考题:
python
# 绘制sin和cos曲线
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), 'r-', label='sin')
plt.plot(x, np.cos(x), 'b--', label='cos')
plt.legend()
📌 知识点4:柱状图(⭐⭐⭐必考)
python
# 基本用法
x = [0,1,2,3]
height = [100,200,150,180]
plt.bar(x, height, width=0.7, color='b')
# 数据标注(常考)
for a,b in zip(x, height):
plt.text(a, b+5, '%.0f'%b, ha='center')
# 多系列并列
barW = 0.3
x1 = [0,1,2,3]
x2 = [i+barW for i in x1]
plt.bar(x1, data1, barW, label='A')
plt.bar(x2, data2, barW, label='B')
📌 知识点5:饼图
python
data = [0.3, 0.2, 0.5]
labels = ['A', 'B', 'C']
explode = (0.1, 0, 0) # 突出第1块
plt.pie(data,
labels=labels,
explode=explode,
autopct='%1.1f%%') # 显示百分比
plt.axis('equal') # 圆形
📌 知识点6:散点图
python
plt.scatter(x, y,
s=50, # 大小
c='red', # 颜色
marker='o', # 标记
alpha=0.5) # 透明度
# 不同颜色分类(常考)
plt.scatter(x1, y1, c='r', marker='*', label='类别1')
plt.scatter(x2, y2, c='g', marker='o', label='类别2')
plt.legend()
📌 知识点7:直方图
python
# 图像灰度直方图(常考)
hd = []
for i in range(row):
for j in range(col):
gray = im[i,j,0]*0.3 + im[i,j,1]*0.59 + im[i,j,2]*0.11
hd.append(gray)
plt.hist(hd, bins=256, color='k')
📌 知识点8:箱形图
python
# 单系列
plt.boxplot(data, labels=['A','B','C'])
# Pandas快速绘制(推荐)
import pandas as pd
df = pd.read_excel('成绩.xlsx')
df.boxplot()
箱形图5个关键点:
- 最小值(下边缘)
- Q1(下四分位数)
- 中位数
- Q3(上四分位数)
- 最大值(上边缘)
📌 知识点9:3D图形(⭐⭐)
python
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
# 或
ax = fig.add_subplot(111, projection='3d')
# 三维曲面
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
ax.plot_surface(X, Y, Z, cmap='rainbow')
# 三维曲线
ax.plot(x, y, z, 'r-')
三、高频考点汇总
🔥 考点1:图例位置
python
plt.legend(loc='upper right') # 或用数字1-10
plt.legend(bbox_to_anchor=(1.2, 0.5)) # 精确定位
| 位置 | 字符串 | 数字 |
|---|---|---|
| 右上 | upper right | 1 |
| 左上 | upper left | 2 |
| 右下 | lower right | 4 |
🔥 考点2:NumPy数据生成
python
# arange:指定步长
np.arange(0, 10, 0.5) # [0, 0.5, 1, ..., 9.5]
# linspace:指定个数
np.linspace(0, 10, 5) # [0, 2.5, 5, 7.5, 10]
# meshgrid:生成网格
x = np.array([1,2,3])
y = np.array([4,5])
X, Y = np.meshgrid(x, y)
# X = [[1,2,3], [1,2,3]]
# Y = [[4,4,4], [5,5,5]]
🔥 考点3:文件数据读取
python
# 文本文件
with open('data.txt', 'r') as f:
dt = f.readlines()
dt = [line.strip().split('\t') for line in dt]
# Excel文件(推荐)
import pandas as pd
df = pd.read_excel('data.xlsx')
x = df['列名1']
y = df['列名2']
四、典型例题速练
例题1:GDP趋势图(必练⭐⭐⭐)
python
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams['font.sans-serif'] = ['SimHei']
# 读取数据
df = pd.read_excel('gdp.xlsx')
years = df['年份']
values = df['产值']
# 绘图
plt.figure(figsize=(10,6))
plt.plot(years, values, 'b-o', linewidth=2)
plt.title('中国GDP变化趋势')
plt.xlabel('年份')
plt.ylabel('GDP(亿元)')
plt.grid(True)
# X轴刻度调整
label = [years[i] for i in range(0, len(years), 5)]
plt.xticks(range(0, len(years), 5), label, rotation=45)
plt.show()
例题2:成绩统计图(必练⭐⭐⭐)
python
# 条形图+饼图组合
fig, axes = plt.subplots(1, 2, figsize=(12,5))
# 子图1:柱状图
plt.subplot(121)
subjects = ['语文','数学','英语']
scores = [85, 92, 78]
colors = ['red','green','blue']
bars = plt.bar(subjects, scores, color=colors, width=0.5)
for bar in bars:
h = bar.get_height()
plt.text(bar.get_x()+bar.get_width()/2, h+2,
f'{h}分', ha='center')
plt.title('各科成绩')
plt.ylabel('分数')
# 子图2:饼图
plt.subplot(122)
grades = [10, 20, 50, 15, 5]
labels = ['优秀','良好','中等','及格','不及格']
explode = (0.1, 0, 0, 0, 0)
plt.pie(grades, labels=labels, explode=explode,
autopct='%1.1f%%')
plt.title('成绩分布')
plt.tight_layout()
plt.show()
例题3:图像处理(必练⭐⭐)
python
from PIL import Image
import numpy as np
# 读取图像
im = np.array(Image.open('pic.jpg'))
# 灰度化
gray = im[:,:,0]*0.3 + im[:,:,1]*0.59 + im[:,:,2]*0.11
# 绘制直方图
plt.figure(figsize=(12,4))
plt.subplot(121)
plt.imshow(im)
plt.title('原图')
plt.subplot(122)
plt.hist(gray.flatten(), bins=256, color='k')
plt.title('灰度直方图')
plt.xlabel('灰度值')
plt.ylabel('像素数')
plt.show()
五、考前必背公式
1. 图像灰度计算
Gray = R*0.3 + G*0.59 + B*0.11
2. 极坐标转换
x = r * cos(θ)
y = r * sin(θ)
r = sin(a*θ) # 花瓣图案
3. 箱形图统计
Q1 = 第25百分位
Q2 = 中位数(第50百分位)
Q3 = 第75百分位
IQR = Q3 - Q1
六、快速检查清单
绘图前:
- 导入库:
import matplotlib.pyplot as plt - 中文字体:
plt.rcParams['font.sans-serif'] = ['SimHei'] - 负号显示:
plt.rcParams['axes.unicode_minus'] = False
绘图时:
- 创建绘图区:
plt.figure()或plt.subplots() - 设置标题:
plt.title() - 设置坐标轴:
plt.xlabel(),plt.ylabel() - 设置图例:
plt.legend()
绘图后:
- 显示图表:
plt.show() - 保存图片:
plt.savefig('name.png')
七、常见错误避坑
- 中文乱码 → 设置字体
- 坐标轴不显示负号 →
unicode_minus=False - 图例位置不对 → 调整
loc参数 - 子图间距太小 →
plt.tight_layout()或plt.subplots_adjust() - 数据类型错误 → 确保列表/数组长度一致
- 3D图不显示 → 导入
Axes3D并设置projection='3d'
八、考试答题技巧
- 看清题目要求:图表类型、数据来源、标注要求
- 先写框架代码:导入库→创建图区→绘图→显示
- 注意细节加分:中文显示、数据标注、图例位置
- 检查完整性:标题、坐标轴标签、图例、网格线
- 时间分配:简单图5分钟,复杂图15分钟
🎓 考前最后提醒
必须熟练掌握的5个函数:
plt.plot()- 折线图plt.bar()- 柱状图plt.scatter()- 散点图plt.pie()- 饼图plt.subplot()- 子图
必须记住的3个设置:
- 中文字体设置
- 坐标轴范围设置
- 图例位置设置
必须练习的3个案例:
- GDP趋势图(折线+数据标注)
- 成绩分析(柱状图+箱形图)
- 图像直方图(文件读取+数组处理)
💯 冲刺90分策略
- 基础题(60分):熟练掌握plot、bar、pie三大图表
- 进阶题(20分):subplot子图、数据标注、图例设置
- 拔高题(10分):3D图形、图像处理、综合应用
考前1小时复习重点:
- 手写一遍中文设置代码
- 默写plot/bar/scatter的参数
- 回顾3个典型例题的完整代码