python基础语法四-数据可视化

书接上回:

python基础语法一-基本数据类型

python基础语法二-多维数据类型

python基础语法三-类

1. plot 函数绘制简单折线图

(1)需要的模块:matplotlib.pyplot

(2)语法:matplotlib.pyplot.plot(x, y, format_string, **kwargs)

x: x轴数据

y: y轴数据

format_string: 控制曲线格式的字符串,包括颜色、线条样式和标记样式

**kwargs: 键值参数,相当于一个字典

例 1 :

import matplotlib.pyplot as plt

import numpy as np

plt.plot(1,2,3,4,5, 2,5,7,4,8)

plt.show()

2. 设置线条颜色

(1)b/g/r/c/m/y/k/w/RGB/灰度值(0-1)

例 2 :

plt.plot(1,2,3,4,5, 2,5,7,4,8, color='r')

plt.plot(1,2,3,4,5, 2,5,7,4,8, color='#FFF000') #RGB

plt.plot(1,2,3,4,5, 2,5,7,4,8, color='0.3') # 灰度值

plt.show()

3. 设置线条样式

(1)实线:'-'

(2)双划线:'--'

(3)点划线:'-.'

(4)虚线:':'

例 3 :

plt.plot(1,2,3,4,5, 2,5,7,4,8, linestyle='-.')

plt.show()

4. 设置标记样式

(1) 设置值 说明 设置值 说明

. 点标记 1 下花三角标记

, 像素标记 2 上花三角标记

o 实心圆标记 3 左花三角标记

v 倒三角标记 4 右花三角标记

^ 上三角标记 s 实心正方形标记

> 右三角标记 p 右花五角形标记

< 左三角标记 * 星形三角标记

例 4 :

plt.plot(1,2,3,4,5, 2,5,7,4,8, marker=',')

plt.plot(1,2,3,4,5, 2,5,7,4,8, marker='o', markerfacecolor='w') # 空心圆,也可以简写成 mfc

plt.show()

5. 画布设置

(1)matplotlib.pyplot.figure(num=None,figsize=None,dpi=None,facecolor=None,edgecolor=None,frameon=True)

num:图像编号或名称,数字为编号,字符串为名称,该参数可激活不同的画布

figsize:画布的宽和高,单位:英寸

dpi:绘图对象的分辨率,每英寸包含的像素数,默认80

facecolor:背景颜色

edgecolor:边框颜色

frameon:是否显示边框,默认True

例 5 :

plt.figure(facecolor='red',figsize=(10,6))

plt.plot(1,2,3,4,5, 2,5,7,4,8)

plt.show()

6. 坐标轴设置

(1)坐标轴标题:xlabel/ylabel,若中文乱码,加上:matplotlib.pyplot.rcParams'font.sans-serif'='SimHei'

(2)坐标轴刻度:xticks/yticks

(3)坐标轴范围:xlim/ylim

(4)网格线:grid

例 6 :

plt.rcParams'font.sans-serif'='SimHei'

plt.xlabel('x 轴 ')

plt.ylabel('y 轴 ')

month = str(i)+'* *月* *' for i in range(1, 11)

plt.xticks(range(1,11), month)

plt.yticks(range(1,11))

plt.xlim(1,11)

plt.ylim(1,11)

plt.grid(color='black', linestyle='--', linewidth='2', axis='y') # axis: 隐藏 y 轴网格线

plt.plot(1,2,3,4,5, 2,5,7,4,8)

plt.show()

7. 文本标签 / 标题 / 图例设置

(1)文本标签:matplotlib.pyplot.text(x,y,s,**kwargs)

(2)标题:matplotlib.pyplot.title()

(3)图例:matplotlib.pyplot.legend() 补充:若legend显示不全,可写成legend((**,)),其中**是要显示的内容

(4)说明:fontsize:字体大小 ha:水平对齐方式 va:垂直对齐方式

(5)位置 说明

best 自适应

lower right 右下方

center left 左中间

center 正中间

upper right 右上方

lower left 左下方

center right 右中间

lower center 下中间

upper left 左上方

right 右侧

upper center 上中间

例 7 :

x = 1,2,3,4,5

y = 2,5,7,4,8

for a,b in zip(x,y):

plt.text(a,b,b,ha='center', va='top',size=15,color='red')

plt.plot(x, y)

plt.show()

8. 其他设置

(1)添加注释:matplotlib.pyplot.annotate(s,xy,xytext,xycoords,arrowprops)

(2)调整图表与画布边缘间距:matplotlib.pyplot.subplots_adjust(left,right,top,bottom) 取值在0-1之间, left<right,top/right的值越大,距离越小;bottom/left的值越大,距离越长

(3)坐标轴刻度线:matplotlib.pyplot.tick_params(bottom,left,right,top) 是否显示刻度线

(4)matplotlib.pyplot.rcParams'xtick.direction'='in' 显示刻度线朝外还是朝里; in:朝里 out:朝外

(5)matplotlib.pyplot.rcParams'ytick.direction'='in'--------->疑问:为什么加上plt.figure()才会起作用?

例 8 :

x = 1,2,3,4,5

y = 2,5,7,4,8

plt.rcParams'font.sans-serif'='SimHei'

plt.subplots_adjust(left=0.2,right=0.5,top=0.5,bottom=0.2)

plt.tick_params(bottom=True,left=True,right=True,top=True)

for a,b in zip(x,y):

plt.text(a,b,b,ha='center', va='top',size=15,color='red')

plt.annotate(' 第二个数 ',xy=(2,5),xytext=(3,5),arrowprops=dict(facecolor='r', shrink=0.05))

plt.figure()

plt.rcParams'xtick.direction'='in'

plt.rcParams'ytick.direction'='in'

plt.plot(x, y)

plt.show()

9. 绘制折线图

例 9 :

student = 'Julie', 'Sunny', 'John', 'Tonny'

Math = 136, 121, 118, 140

Chinese = 96, 55, 120, 118

English = 150, 120, 138, 144

plt.plot(student, Math,label='Math',color='red',marker='o')

plt.plot(student, Chinese,label='Chinese',color='yellow',marker='o',linestyle='--')

plt.plot(student, English,label='English',color='green',marker='o',linestyle=':')

plt.legend('Math','Chinese','English')

plt.show()

10. 绘制柱形图

(1)格式:plt.bar(x, height, width, *, align='center', **kwargs)

x : x轴数据

height : 柱子的高度,即y轴的数据

align : 对齐方式

kwargs : 关键字参数,如color/alpha/label

例 10 :

student = 'Julie', 'Sunny', 'John', 'Tonny'

Math = 136, 121, 118, 140

plt.bar(student,Math,align='center')

plt.show()

11. 绘制多柱形图

例 11 :

student_raw = 'Julie', 'Sunny', 'John', 'Tonny'

student = np.array(0,1,2,3) # 将列表转成数组

Math = 136, 121, 118, 140

Chinese = 96, 55, 120, 118

English = 150, 120, 138, 144

plt.xlabel('student')

plt.ylabel('grade')

bar_width=0.2

plt.bar(student,Math,bar_width,color='blue')

plt.bar(student+bar_width,Chinese,bar_width,color='green')

plt.bar(student+bar_width*2,English,bar_width,color='red')

plt.xticks(student,student_raw)

for a,b in zip(student, Math):

plt.text(a,b,format(b,','),ha='center',va='center')

for a,b in zip(student, Chinese):

plt.text(a+bar_width,b,format(b,','),ha='center',va='center')

for a,b in zip(student, English):

plt.text(a+bar_width*2,b,format(b,','),ha='center',va='center')

plt.legend('Math','Chinese','English')

plt.show()

12. 绘制直方图

(1)直方图作用:如想要查看一个班学生们数学成绩在0-100每个分数段的人数分布

(2)格式:plt.hist(x,bins)

x : 数据集,最终的直方图将对数据集进行统计

bins : 统计数据的区间分布

例 12 :

x = 55, 67, 89, 100, 45, 86, 89

bins = 0,60,70,80,90,100

plt.xticks(bins)

plt.xlabel('grade')

plt.ylabel('student number')

plt.title('student math grade distribution diagram')

plt.hist(x,bins,edgecolor='black')

plt.show()

13. 绘制饼形图

(1)格式:plt.pie(x,labels,colors,labeldistance,autopct,startangle,radius,center, textprops)

x: 每一块饼形图的比例

labels: 每一块饼形图外侧显示的说明文字

labeldistance: 标记的绘制位置,相对于半径的比例,默认1.1

autopct: 设置饼图百分比,可以使用格式化字符串或者format函数

startangle: 起始绘制角度, 默认是x轴正方向逆时针开始画

radius: 饼图半径,默认1

center: 浮点类型的列表,可选参数,默认值为(0,0)表示图表中心位置

textprops: 设置标签和比例文字的格式,字典类型

例 13 :

x = 5,10,30

labels = 'one ball', 'two balls', 'three balls'

plt.pie(x,labels=labels,autopct='%1.1f%%',textprops={'fontsize':12})

plt.axis('equal') # 设置 x/y 轴刻度一致,保证饼形图是圆形

plt.legend(labels,loc='lower left')

plt.show()

相关推荐
天天被压力1 小时前
【A股分钟级高频数据完全手册 #07】北交所历史分钟K线接口:京市Pro版分时批量
java·人工智能·python
天天被压力1 小时前
【A股分钟级高频数据完全手册 #08】股票日、分时数据接口对比:普通分时与Pro版差异实测
java·人工智能·python
特立独行的猫A2 小时前
AI 时代,我为什么推荐用 cj-tauri 开发桌面应用
java·后端·python
小lo想吃棒棒糖2 小时前
把机器人训练从 GPU 搬到昇腾 NPU:启元 Q1 起身动作 PPO 训练全记录
python·机器人·昇腾·启元机器人
Thanks_ks2 小时前
【第 006 讲】搭建 PyCharm 开发环境:PyCharm 的下载与安装 | 初始设置与常用配置
ide·python·pycharm·开发工具·jetbrains·开发环境·集成开发环境
青少儿编程课堂3 小时前
蓝桥杯青少组图形化省考报名倒计时·全国青少年信息素养大赛·电子学会图形化考级:校园黑白棋人机对战解析
c++·python·算法·bfs·信息学竞赛
tellmewhoisi3 小时前
nlp:知识库检索和dify知识库创建
python·自然语言处理
2601_968793144 小时前
Python Requests 轻量自动化:无需浏览器,实现真人级账号浏览模拟
开发语言·python·自动化
段一凡-华北理工大学13 小时前
工业智能体:从Codex/Claude到项目实战~系列文章05:从“AI助手“到“工业智能体“:能力跃迁与落地范式
人工智能·python·claude·codex·工业智能体·高炉炼铁智能化
深蓝AI13 小时前
ContextVar 到线程池就丢了?asyncio.to_thread 和 run_in_executor 实测
python