Python可视化绘图基础

Python绘图基础

【代码框2-19】------matplotlib绘图的一些基本操作

python 复制代码
# 图2-2的绘制代码
# 导入相关模块
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'      # 显示中文
plt.rcParams['axes.unicode_minus']=False        # 显示负号

# 生成绘图数据
np.random.seed(2025)                           # 设置随机数种子
x = np.random.standard_normal(200)             # 生成200个标准正态分布随机数
y = 1 + 2 * x + np.random.normal(0, 1, 200)    # 生成变量y的随机数

# 绘制图像内容
plt.figure(figsize=(8, 6))                     # 设置图形大小(长度和高度)
plt.scatter(x, y, marker='o',color='white',edgecolors='blue') 
                                               # 绘制散点图,设置c=''可绘制空心

fit = np.poly1d(np.polyfit(x, y, deg=1))       # 使用一项式拟合
y_hat = fit(x)                                 # 得到拟合y值
plt.plot(x, y_hat, c='r')                      # 绘制拟合直线,设置为红色
plt.plot(x.mean(), y.mean(), 'ro', markersize=20, fillstyle='bottom')
                                         # 添加均值点并设置点的大小、颜色和填充类型
plt.axhline(y.mean(), color='black', ls='-.', lw=1)          # 添加y的均值水平线
plt.axvline(x.mean(), color='black', ls=(0, (5, 10)),lw=1)   # 添加x的均值垂直线

# 绘制其他组件
plt.grid(linestyle=':')                  # 添加网格线

ax = plt.gca()                           # 得到当前操作的图像
ax.spines['right'].set_color('green')    # 设置边框颜色
ax.spines['left'].set_color('#4169E1')
ax.spines['top'].set_color('royalblue')
ax.spines['bottom'].set_color('b')

plt.text(x=0.4, y=-2, s=r'$\hat{y}=\hat{\beta}_0+\hat{\beta}_1x$',
         fontdict={'size':12, 'bbox':{'fc': 'pink', 'boxstyle': 'round'}}, ha='left')  
                                                             # 添加文本注释

plt.annotate(text=r'均值点', xy=(x.mean(), y.mean()), xytext=(-0.6, 3),
         arrowprops = {'headwidth': 10, 'headlength': 12, 'width': 2,
                       'facecolor': 'r', 'shrink': 0.1,},fontsize=14, 
                       color='red', ha='right')               # 添加带箭头的文本注释

plt.title('散点图及拟合直线\n并为图形增加新的元素', fontsize=14) # 添加标题,\n表示换行
plt.xlabel('x = 自变量', fontsize=12)   # 添加x轴标题
plt.ylabel('y = 因变量', fontsize=12)   # 添加y轴标题
plt.legend(['拟合直线'], loc='best',fontsize=10)  # 添加图例

plt.show()                                        # 显示图像

【代码框2-20】------图形布局

python 复制代码
# 使用subplots函数等分布局(见图2-3)
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1010)   # 数值随机数种子
plt.subplots(nrows=2, ncols=2, figsize=(7, 5))# 生成2x2网格,整幅图形宽度为8,高度为6

plt.subplot(221)        # 在2x2网格的第1个位置绘图
plt.scatter(x=range(50), y=np.random.randint(low=0, high=100, size=50), 
            marker='*', c='red')       # 绘制散点图
plt.title('subplot(221)')              # 绘制标题 

plt.subplot(222)        # 在2x2网格的第2个位置绘图
plt.plot(range(20), np.random.normal(5,10,20), marker='o', 
         linestyle='-.', linewidth=2, markersize=5)    # 绘制折线图
plt.title('subplot(222)')

plt.subplot(223)        # 在2x2网格的第3个位置绘图
plt.bar(x=range(5), height=range(5, 0, -1), color=['cyan', 'pink'])  # 绘制条形图
plt.title('subplot(223)')

plt.subplot(224)        # 在2x2网格的第4个位置绘图
plt.hist(np.random.normal(loc=50, scale=10, size=500), 
         bins=10, color='lightgreen')  # 绘制直方图
plt.title('subplot(224)')

plt.tight_layout()     # 紧凑布局

# 使用plt.savefig('./图2-3 subplots函数的布局.jpg') 可保存图片
python 复制代码
# 使用GridSpec函数自定义布局(见图2-4)
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(6, 5))   # 创建新图形,并设置图形大小
grid=plt.GridSpec(3,3)             # 生成3行3列的网格
plt.subplot(grid[0,:2])            # 占据第1行前2列
plt.subplot(grid[0,2])             # 占据第1行第3列
plt.subplot(grid[1,:1])            # 占据第2行第1列
plt.subplot(grid[1,1:])            # 占据第2行后2列
plt.subplot(grid[2,:3])            # 占据第3行前3列

fig.tight_layout()                 # 紧凑布局
python 复制代码
# 使用add_gridspec函数布局(见图2-5)
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1010)
fig = plt.figure(figsize=(7, 4))
spec = fig.add_gridspec(nrows=2, ncols=6,width_ratios=[1,1,1,1,1,1], height_ratios=[1,2])
fig.add_subplot(spec[0, 1:3])       # 占据第1行的2~3列
fig.add_subplot(spec[0, 3:])        # 占据第1行的后3列
ax = fig.add_subplot(spec[:, 0])     # 占据第1列
ax = fig.add_subplot(spec[1, 1:4])   # 占据第2行的2~4列
ax = fig.add_subplot(spec[1, 4:])    # 占据第2行第4列后的所有列(这里为5~6列)
fig.tight_layout()
相关推荐
uppp»25 分钟前
深入理解 Java 反射机制:获取类信息与动态操作
java·开发语言
Yan-英杰27 分钟前
百度搜索和文心智能体接入DeepSeek满血版——AI搜索的新纪元
图像处理·人工智能·python·深度学习·deepseek
weixin_307779131 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
多想和从前一样5 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
ll7788115 小时前
LeetCode每日精进:20.有效的括号
c语言·开发语言·算法·leetcode·职场和发展
小喵要摸鱼6 小时前
【Pytorch 库】自定义数据集相关的类
pytorch·python
bdawn7 小时前
深度集成DeepSeek大模型:WebSocket流式聊天实现
python·websocket·openai·api·实时聊天·deepseek大模型·流式输出
Jackson@ML7 小时前
Python数据可视化简介
开发语言·python·数据可视化
mosquito_lover17 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt