IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> 《python数据科学》-Matplotlib -> 正文阅读

[Python知识库]《python数据科学》-Matplotlib

3 Matplotlib

3.1 figure、axes、axis

ax1 = plt.subplot(221)
ax2 = plt.subplot(222)
ax3 = plt.subplot(223)
ax4 = plt.subplot(224)
plt.show()

在这里插入图片描述
由上图可以看出,figure是一个画布,一个画布上可以画多个坐标系(axes),每个(二维)坐标系有两个轴(axis),相信大家看到上图就能够知道画布,坐标系和坐标轴三者之间的关系。

3.2 图像布局

3.2.1 plt.subplot()

上例中使用的也是一种图像布局的方法,将一个画布分成四个部分,将四个坐标系分别命名成ax1,ax2,ax3,ax4

3.2.2 plt.subplots()

fig,ax=plt.subplots(2,2)
ax[0,0].plot([1,2,3],[1,2,3])
ax[0,1].scatter([1,2,3],[1,2,3])
ax[1,0].bar([1,2,3],[1,2,3])
ax[1,1].pie([10,20,30])
plt.show()

在这里插入图片描述

3.3 折线图-plt.plot()

面向对象制图

fig = plt.figure(figsize=(8,6)) # 创建一个画布
axes = fig.add_subplot()        # 新建一个子坐标系
axes.plot([0,1,2,3,4,5], [1,2,4,6,8,9],c='r',ls=':',marker='o',markersize='10',mec='b',mfc='y')  # 画折线图
axes.plot([1,3],c='b',ls='-.')
axes.plot([1,4],c='g',ls='--')
axes.plot([1,5],c='y',ls='-')
axes.grid(True,color='r', linestyle='-', linewidth=2, alpha=0.2)  # 添加背景方格
axes.set_xmargin(0) #图形到底边的距离
axes.set_ymargin(0) #图形到左边的距离
plt.show()

在这里插入图片描述

使用循环画多个图

fig = plt.figure(figsize=(8,6)) # 新建画布
config = { 
    'c':['r','g','b','y'],
    'ls':['-','-.','--',':'],
    'lw':[1,2,3,4],
} # 配置项
ax = fig.add_subplot() # 添加坐标系
for i in range(4):
    ax.plot([1,i+2],c=config['c'].pop(),ls=config['ls'].pop(),lw=config['lw'].pop())
# 循环画四个折线图
plt.show()

在这里插入图片描述> 常用参数说明

xdata,ydata : # 具有相同维度的数据 
c or color  : # 颜色 
# 常用颜色列表:
=============    ===============================
character        color
=============    ===============================
``'b'``          blue
``'g'``          green
``'r'``          red
``'c'``          cyan
``'m'``          magenta
``'y'``          yellow
``'k'``          black
``'w'``          white
=============    ===============================
linestyle or ls : # 线型
# 支持的线型:
=============    ===============================
character        description
=============    ===============================
``'-'``          solid line style
``'--'``         dashed line style
``'-.'``         dash-dot line style
``':'``          dotted line style
=============    ===============================
linewidth or lw : #  线宽 float
marker :         #  数据点的类型
# 常用的marker:
=============   ===============================
character       description
=============   ===============================
``'.'``         point marker
``','``         pixel marker
``'o'``         circle marker
``'v'``         triangle_down marker
``'^'``         triangle_up marker
``'<'``         triangle_left marker
``'>'``         triangle_right marker
``'1'``         tri_down marker
``'2'``         tri_up marker
``'3'``         tri_left marker
``'4'``         tri_right marker
``'8'``         octagon marker
``'s'``         square marker
``'p'``         pentagon marker
``'P'``         plus (filled) marker
``'*'``         star marker
``'h'``         hexagon1 marker
``'H'``         hexagon2 marker
``'+'``         plus marker
``'x'``         x marker
``'X'``         x (filled) marker
``'D'``         diamond marker
``'d'``         thin_diamond marker
``'|'``         vline marker
``'_'``         hline marker
=============   ===============================
markeredgecolor or mfc :        #数据点的边框颜色
markeredgewidth or mew: float   #数据点的边框粗细
markerfacecolor or mfc: color   #数据点前景色
markersize or ms: float         #数据点的大小
markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]                      #每个点是不是应该有数据
# 对于上面的第一个例子
# 设置:markevery=[False,True,True,False,False,False]
# 则那么只有(1,2),(2,4)这两个点显示
fmt = '[marker][line][color]' 
# 可以将marker=’o‘,line=':',color='r' 简写成 ‘o:r’

3.4 散点图-plt.scatter()

fig = plt.figure()
ax = fig.add_subplot()
ax.scatter(x=np.random.randn(50),y=np.random.randn(50),s=np.random.randint(0,100,50),c=np.random.randn(50),marker='*')
plt.show()
# s : size 
# c : color 
# 其余参数和plot都差不多

在这里插入图片描述

3.5 柱状图-plt.bar()

垂直柱状图

plt.rcParams['font.sans-serif'] = "SimHei"
fig = plt.figure()
ax = fig.add_subplot()
x = ['裤子','上衣','袜子']
y1 = [14,20,23]
y2 = [17,19,32]
ax.bar(
    x=x,     # x坐标
    height=y1,  # 柱状图高度
    width=0.2,  # 柱状图高度
    align='center', # 对齐方式'center' or ‘edge’
    bottom=0, # 底部坐标
    color = 'b', # 颜色 字符或者字符列表
    edgecolor = 'y', # 边框颜色
    linewidth = 5,  # 边框宽度
    # tick_label = [], 修改x轴的标注
)
ax.set_label('男生')
ax.bar(
    x=x,
    height=y2,
    width=0.2,
    align='center',
    bottom=y1,
    color = 'r',
    edgecolor = 'y',
    linewidth = 5,
    # tick_label = [], 修改x轴的标注
)

ax.set_label("女生")
ax.legend(["男","女"]) # 设置图例
plt.show()

在这里插入图片描述

横向柱状图

plt.rcParams['font.sans-serif'] = "SimHei"
fig = plt.figure()
ax = fig.add_subplot()
x = ['裤子','上衣','袜子']
y1 = [14,20,23]
ax.barh(y=x,width=y1,height=0.8,left=[0,0,5])

ax.legend("销量")
plt.show(

在这里插入图片描述

直方图

hz,bins = np.histogram(np.random.randint(1,100,5000),bins=np.linspace(0,100,100))
hz,bins
plt.bar(x=bins[:-1],height=hz)

在这里插入图片描述

3.6 饼状图-plt.pie()

plt.rcParams['font.sans-serif'] = "SimHei"
fig = plt.figure()
ax = fig.add_subplot()
ax.pie(x=[12,45,23],explode=np.array([0,0,0.2]),labels=list("中美日"),colors=list('rgb'),autopct='%1.1f%%',shadow=True)
plt.show()

#参数说明:

在这里插入图片描述

3.7 fontdict

# 默认设置
{'fontsize': 	rcParams['axes.titlesize'],
                'fontweight': rcParams['axes.titleweight'],
                'color': rcParams['axes.titlecolor'],
                'verticalalignment': 'baseline',
                'horizontalalignment': loc}

附件0 综合练习

x = np.arange(-5,6,1) # X轴测试数据
y = 2*x + 5			  # Y轴测试数据
fig, ax = plt.subplots(1,1)		# 新建一个画布,一个坐标系
ax.set_title("Test Axes",fontdict={'size':16,'color':'b'}) # 设置一个标题
ax.spines['right'].set_color(None)	# 设置坐标系右边的轴不显示
ax.spines['top'].set_color(None)	# 设置坐标系上面的轴不显示
ax.set_xlim(-5,+5)					# 显示X轴的范围是-5 ~ +5
ax.set_xticks(np.arange(-5,6,1))	# 显示X轴的标记点是[-5,6)左闭右开区间,间隔为1
ax.set_ylim(-20,+20)				# 设置y轴的范围是-20 ~ +20
ax.set_xlabel('X',loc='right')		# 设置x轴的标记为X,位置靠右
ax.set_ylabel('y',loc='top')		# 设置Y轴的标记为Y,位置靠上
ax.spines['bottom'].set_position(('data',0))	# 设置底部的轴在左侧数值轴为0的位置
ax.spines['left'].set_position(('data',0))		# 设置左侧的轴在底部数值轴为0的位置
ax.annotate('$y=2x+5$',xy=(3,16))				# 设置标记
ax.scatter(x=(-5/2),y=0,c='b') # scatter是画一个点,x表示x轴的位置,y表示y轴的位置,c表示颜色
ax.scatter(x=0,y=5,c='b') # scatter是画一个点,x表示x轴的位置,y表示y轴的位置
ax.scatter(x=2,y=9,c='b') 
plt.scatter(x=(2,)*10,y=np.linspace(0,9,10),s=1,c='b') # 使用点线画一条虚线
plt.scatter(x=np.linspace(0,2,10),y=(9,)*10,s=1,c='b')
ax.plot(x,y) # plot画一条直线
plt.show()   # 显示图像

如下图所示
在这里插入图片描述

附件1 所有配置项

plt.rcParams.keys()

附件2 常用配置项

# 显示中文
plt.rcParams['font.sans-serif'] = 'SimHei'
#设置正常显示字符(负号)
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['savefig.dpi'] = 300 #图片像素
plt.rcParams['figure.dpi'] = 300 #分辨率
plt.rcParams['figure.figsize'] = (8.0, 4.0)    # 图像显示大小
plt.rcParams['image.interpolation'] = 'nearest' # 最近邻差值: 像素为正方形
#Interpolation/resampling即插值,是一种图像处理方法,它可以为数码图像增加或减少象素的数目。
plt.rcParams['image.cmap'] = 'gray' # 使用灰度输出而不是彩色输出

结语

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2021-07-25 16:14:00  更:2021-07-25 16:14:02 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年4日历 -2024/4/28 21:54:19-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码