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()

相关推荐
张张123y5 小时前
后端第一课:输入 URL 后发生了什么?我用手写 Socket 把全链路跑通了
python·websocket·ai·socket·url·后端开发
全栈弄潮儿7 小时前
Python实战第7期:字典与集合
后端·python·编程语言
2603_965148118 小时前
电商选品调研:通过关键词搜索API获取市场热销商品,结合商品详情API分析竞品卖点与定价
开发语言·数据库·人工智能·python·信息可视化
xixiaoyunya8 小时前
Python 异步编程入门:用 asyncio 轻松实现并发任务
开发语言·python·php
把我格子衫拿来8 小时前
Dice 很高就够了吗?分割评价中的 IoU、表面距离与 HD95
python·图像分割·模型评估·医学影像·dice
曲径海盗9 小时前
【Python 学习第 31 天】复习:变量与数据类型 等 3 题
python·学习笔记·编程入门
Data_Journal9 小时前
如何绕过 Cloudflare:网页抓取的最佳方法
网络·python
我命由我1234510 小时前
智能助手通用问答边界
人工智能·python·学习·ai·学习方法·ai编程·智能体
Angeldream12310 小时前
第 4 章 医学影像预处理
图像处理·人工智能·python·医学影像·医学影像处理
Web3&Basketball10 小时前
实测Gemini4Argon:ERQA 87%登顶长程任务榜
数据库·python·大模型·多模态·gemini·长上下文·推理优化