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

相关推荐
waynaqua10 分钟前
FastAPI开发AI应用一:实现连续多轮对话
python·openai
纨妙13 分钟前
python打卡day59
开发语言·python
waynaqua14 分钟前
FastAPI开发AI应用二:多厂商模型使用指南
python·openai
秋难降17 分钟前
Python 知识 “八股”:给有 C 和 Java 基础的你😁😁😁
java·python·c
FF-Studio30 分钟前
大语言模型(LLM)课程学习(Curriculum Learning)、数据课程(data curriculum)指南:从原理到实践
人工智能·python·深度学习·神经网络·机器学习·语言模型·自然语言处理
像风一样的男人@1 小时前
python --货车装厢问题
开发语言·python
Y1nhl1 小时前
力扣_链表_python版本
开发语言·python·算法·leetcode·链表·职场和发展
qianbo_insist2 小时前
c++ python 共享内存
开发语言·c++·python
凌览2 小时前
有了 25k Star 的MediaCrawler爬虫库加持,三分钟搞定某红书、某音等平台爬取!
前端·后端·python
这里有鱼汤3 小时前
给你的DeepSeek装上实时行情,让他帮你炒股
后端·python·mcp