当前位置: 首页 > article >正文

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


http://www.kler.cn/news/294896.html

相关文章:

  • HTTP与HTTPS在软件测试中的解析
  • 使用modelsim小技巧
  • Mysql数据库表结构迁移PostgreSQL
  • springboot组件使用-mybatis组件使用
  • 《云原生安全攻防》-- K8s攻击案例:高权限Service Account接管集群
  • IPv6归属地查询-IPv6归属地接口-IPv6归属地离线库
  • 【有啥问啥】什么是扩散模型(Diffusion Models)?
  • [论文笔记] LLaVA
  • Effective Java学习笔记--39-41条 注解
  • 【LVI-SAM】激光雷达点云处理特征提取LIO-SAM 之FeatureExtraction实现细节
  • 把Django字典格式的数据库配置转成tortoise-orm的URL格式
  • k8s集群版部署
  • 排序算法-std::sort的使用(待学习第一天)
  • llama.cpp demo
  • 【H2O2|全栈】关于HTML(2)HTML基础(一)
  • 数字证书与HTTPS部署
  • 亚马逊云科技 Gen BI 2024-09-04 上海站QuickSight
  • Ajax 解决回调竞争
  • C# System.Linq提供类似SQL语法的高效查询操作
  • 吐血整理 ChatGPT 3.5/4.0 新手使用手册~ 【2024.09.03 更新】
  • 大厂嵌入式数字信号处理器(DSP)面试题及参考答案
  • 电动机制造5G智能工厂工业物联数字孪生平台,推进制造业数字化转型
  • Shell编程:正则表达式(通配符、正则概念、元字符、量词、示例等)
  • 【C++ 面试 - 新特性】每日 3 题(四)
  • 【Unity小技巧】URP管线遮挡高亮效果
  • c++标准库中对文件读写的函数与类
  • arm-linux-gnueabihf-gcc -Wall -nostdlib -c -O2 -o start.o start.s
  • 景联文科技:专业图像采集服务,助力智能图像分析
  • 关于 ubuntu系统install的cmake版本较低无法编译项目升级其版本 的解决方法
  • Vue 3中的 路由守卫:全面解析与使用教程