使用Matplotlib美化和修饰图形

人工智能58

1. 调整坐标轴和刻度

作为函数图像的必要组成部分,轴和尺度直接反映了图形中变量的数值尺度的范围。

[En]

As a necessary part of the function image, the axis and scale directly reflect the range of the numerical scale of the variables in the graph.

适当的调整和美化坐标轴及刻度能够让图形一目了然。

1.1 设置坐标轴刻度

刻度是图形的一部分,由刻度定位器(Tick Locator)和刻度格式器(Tick Formatter)两部分组成,其中刻度定位器用于制定刻度所在的位置,刻度格式器用于制定刻度显示。

刻度分为主刻度(Major Ticks)和次刻度(Minor Ticks),可以分别制定二者的位置和格式,次刻度默认为不显示。

为了展示设置刻度参数的效果,可以先使用plot()函数生成一条余弦曲线,代码如下:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import AutoLocator,MultipleLocator,FormatStrFormatter
x=np.linspace(0,5,100)
y=np.cos(x)
fig=plt.figure(figsize=(4,4))
ax=fig.add_subplot(111)
ax.plot(x,y,lw=2)
plt.show()

使用Matplotlib美化和修饰图形

接着设置坐标轴范围和主,次坐标轴

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import AutoMinorLocator,MultipleLocator,FormatStrFormatter
x=np.linspace(0,5,100)
y=np.cos(x)
fig=plt.figure(figsize=(4,4))
ax=fig.add_subplot(111)

ax.set_xlim(0,5)
ax.set_ylim(-1.5,1.5)
ax.xaxis.set_major_locator(MultipleLocator(1)) #将主刻度设为1的倍数
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(5))

ax.plot(x,y,lw=2)
plt.show()

使用Matplotlib美化和修饰图形

可以看到,在手动设置轴的范围并添加次轴后,水平轴的两个主比例尺被等分成两个相等的部分。

[En]

It can be seen that after manually setting the range of the axis and adding the secondary axis, the two main scales of the horizontal axis are equally divided into two equal parts.

纵轴的两个刻度之间被平均分成了5等分,而且曲线的弯曲程度也随之发生了一些变化。

1.2 设置坐标轴的标签文本

为了显示与二级刻度对应的值,可以使用以下代码调整轴刻度的显示样式

[En]

In order to display the value corresponding to the secondary scale, you can adjust the display style of the axis scale using the following code

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import AutoMinorLocator,MultipleLocator,FormatStrFormatter
x=np.linspace(0,5,100)
y=np.cos(x)
fig=plt.figure(figsize=(4,4))
ax=fig.add_subplot(111)

ax.set_xlim(0,5)
ax.set_ylim(-1.5,1.5)
ax.xaxis.set_major_locator(MultipleLocator(1)) #将主刻度设为1的倍数
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(5))

ax.xaxis.set_minor_formatter(FormatStrFormatter('%5.1f')) #设置x轴标签文本格式
ax.yaxis.set_minor_formatter(FormatStrFormatter('%5.1f'))
ax.tick_params(which='minor',length=5,width=1,labelsize=8,labelcolor='r')
ax.tick_params('y',which='major',length=8,width=1,labelsize=10,labelcolor='b')
ax.plot(x,y,lw=2)
plt.show()

使用Matplotlib美化和修饰图形

1.3 绘制刻度的网格线

为了更直观地查看图表中某些点的值,您可以向图表添加网格线。下面的代码添加由蓝色虚线表示的主比例尺的网格线。

[En]

In order to see the values of some points of the graph more intuitively, you can add gridlines to the graph. the following code adds the gridlines of the main scale, represented by blue dotted lines.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import AutoMinorLocator,MultipleLocator,FormatStrFormatter
x=np.linspace(0,5,100)
y=np.cos(x)
fig=plt.figure(figsize=(4,4))
ax=fig.add_subplot(111)

ax.set_xlim(0,5)
ax.set_ylim(-1.5,1.5)
ax.xaxis.set_major_locator(MultipleLocator(1)) #将主刻度设为1的倍数
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(5))

ax.xaxis.set_minor_formatter(FormatStrFormatter('%5.1f')) #设置x轴标签文本格式
ax.yaxis.set_minor_formatter(FormatStrFormatter('%5.1f'))
ax.tick_params(which='minor',length=5,width=1,labelsize=8,labelcolor='r')
ax.tick_params('y',which='major',length=8,width=1,labelsize=10,labelcolor='b')

ax.grid(ls=':',lw=0.8,color='b')
ax.plot(x,y,lw=2)
plt.show()

使用Matplotlib美化和修饰图形

1.4 移动坐标轴的位置

许多人认为图形只能在笛卡尔坐标系的第一象限内绘制。事实上,有时可以通过移动坐标轴载体和设置比例线的位置来移动坐标轴,从而达到图形在四个象限内完整显示的目的。下面的代码以四个象限显示余弦函数,为了图形美观而增加画布大小。

[En]

Many people think that graphics can only be drawn in the first quadrant of the Cartesian coordinate system. In fact, sometimes it is possible to move the coordinate axis by moving the coordinate axis carrier and setting the position of the scale line, so as to achieve the purpose of complete display of the graph in four quadrants. The following code displays the cosine function in four quadrants, increasing the canvas size for the sake of graphic beauty.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import AutoMinorLocator,MultipleLocator,FormatStrFormatter
x=np.linspace(-5,5,100)
y=np.cos(x)
fig=plt.figure(figsize=(8,6))
ax=fig.add_subplot(111)

ax.set_xlim(-5,5)
ax.set_ylim(-1.5,1.5)
ax.xaxis.set_major_locator(MultipleLocator(1)) #将主刻度设为1的倍数
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(5))

ax.xaxis.set_minor_formatter(FormatStrFormatter('%5.1f')) #设置x轴标签文本格式
ax.yaxis.set_minor_formatter(FormatStrFormatter('%5.1f'))
ax.tick_params(which='minor',length=5,width=1,labelsize=8,labelcolor='r')
ax.tick_params('y',which='major',length=8,width=1,labelsize=10,labelcolor='b')

ax.spines['right'].set_color('b')
ax.spines['top'].set_color('r')
ax.spines['bottom'].set_color('y')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.grid(ls=':',lw=0.8,color='b')
ax.plot(x,y,lw=2)
plt.show()

使用Matplotlib美化和修饰图形

2. 添加标题,图例和注释文本

好的图形需要给出适当的标题、适当的注释和必要的图例,以便于读者理解图形的功能和没有部件的含义。

[En]

Good graphics need to give appropriate titles, appropriate notes and necessary legends to facilitate readers to understand the function of graphics and the meaning of no part.

2.1 设置标题的展示样式

设置图形的标题可以通过title()函数实现,以下代码使用蓝色20号楷体字为上图添加了标题

plt.title('余弦函数在[-5,5]的图像',family='STXINWEI',size=20,color='b',loc='right')

2.2 添加注释文本

分为指向性注释和非指向性注释 分别使用annotate()函数和text()函数实现

ax.annotate('y=sin(x)',xy=(2.5,0.6),xytext=(3.5,0.6),arrowprops=dict(arrowstyle='->',facecolor='black'))
ax.text(-2.1,0.65,'y=cos(x)',color='b',bbox=dict(facecolor='black',alpha=0.2))

annotate()和text()的主要区别是annotate()可以使用arrowprops参数添加箭头,使用xytext参数添加文本

上述示例运行结果如下:

使用Matplotlib美化和修饰图形

3.设置线性和文本字体

3.1 设置线型样式

常用四种线型:点虚线,点画线,破折线,实直线

import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax=fig.add_subplot(111)
linestyles=['-','--','-.',':']
x=np.arange(1,11,1)
y=np.linspace(1,1,10)
for i ,ls in enumerate(linestyles):
    ax.text(0,i+0.5,"{}".format(ls),family='Arial',color='b',weight='black',size=12)
    ax.plot(x,(i+0.5)*y,ls=ls,color='r',lw=3)
ax.set_xlim(-1,11)
ax.set_ylim(0,4.5)
ax.set_xticks([])
ax.set_yticks([]) #可以不显示坐标轴的值
plt.show()

使用Matplotlib美化和修饰图形

下面介绍常用标记样式

import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax=fig.add_subplot(111)
linemarkernames=['. 点形',
                 'o 圆圈',
                 'v 向下的三角形',
                 '^ 向上的三角形',
                 '< 向左的三角形',
                 '> 向右的三角形',
                 's 正方形',
                 'p 五边形',
                 '* 星形',
                 '+ +形',
                 'x x形',
                 '| 竖线',
                 '_ 横线',]
linemarkerstyles=['.','o','v','^','','s','p','*','+','x','|','_']
x=np.arange(5,11,1)
y=np.linspace(1,1,6)
print(y)
for i,marker in enumerate(linemarkerstyles):
    ax.text(0,i*1.8+1,linemarkernames[i],family='STXINWEI',color='b',weight='black',size=12)
    ax.plot(x,i*1.8*y+1,marker=marker,color='r',ls=':',lw=2,markersize=6)

ax.set_xlim(-1,11)
ax.set_ylim(0,24)
ax.margins(0.3)
ax.set_xticks([])
ax.set_yticks([])
plt.show()

使用Matplotlib美化和修饰图形

3.2 设置文本属性和字体属性

import  matplotlib.pyplot as plt
families=['arial','tahoma','verdana']
sizes=['xx-small','x-small','small','medium','large','x-large','xx-large']
styles=['normal','italic','oblique']
variants=['normal','small-caps']
weights=['light','normal','medium','roman','semibold','demibold','demi',
         'bold','heavy','extra bold','black']
fig=plt.figure()
ax=fig.add_subplot(111)
ax.set_xlim(0,9)
ax.set_ylim(0,100)
y=0
size=sizes[0]
style=styles[0]
weight=weights[0]
variant=variants[0]
for family in families:
    x=0
    y=y+6
    for size in sizes:
        y=y+4
        samply=family+' '+size
        ax.text(x,y,samply,family=family,size=size,style=style
                ,weight=weight)
y=0
family=families[0]
size=sizes[4]
variant=variants[0]
for weight in weights:
    x=5
    y=y+0.5
    for style in styles:
        y=y+3
        samply=weight+' '+style
        ax.text(x, y, samply, family=family, size=size, style=style
                , weight=weight)

ax.set_axis_off() #不显示坐标轴
plt.show()

使用Matplotlib美化和修饰图形

python共有3种设置文字属性的方法

(1)对每个函数的每个参数单独指定取值,确定字体,字号,颜色等效果

(2)使用字典存储字体,字号,颜色等属性和取值,作为函数的关键字参数传入

(3)通过调整属性字典rcParams中的字体,字号,颜色等属性值实现

以下代码指定图形中文本的通用字体、字体大小、颜色以及曲线的通用对齐和宽度。

[En]

The following code specifies a common font, font size, color for the text in the drawing, and a common alignment and width for the curve.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import AutoMinorLocator,MultipleLocator,FormatStrFormatter
x=np.linspace(-5,5,100)
y=np.cos(x)
y1=np.sin(x)
elements=['正弦函数','余弦函数']
fig=plt.figure(figsize=(8,6))
ax=fig.add_subplot(111)

plt.rcParams['lines.linewidth']=2
plt.rcParams['lines.linestyle']='-'
plt.rcParams['font.family']='STXINWEI'
plt.rcParams['font.style']='normal'
plt.rcParams['font.weight']='black'
plt.rcParams['font.size']='14'
plt.rcParams['text.color']='black'

ax.set_xlim(-5,5)
ax.set_ylim(-1.5,1.5)
ax.xaxis.set_major_locator(MultipleLocator(1)) #将主刻度设为1的倍数
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(5))

ax.xaxis.set_minor_formatter(FormatStrFormatter('%5.1f')) #设置x轴标签文本格式
ax.yaxis.set_minor_formatter(FormatStrFormatter('%5.1f'))
ax.tick_params(which='minor',length=5,width=1,labelsize=8,labelcolor='r')
ax.tick_params('y',which='major',length=8,width=1,labelsize=10,labelcolor='b')

ax.spines['right'].set_color('b')
ax.spines['top'].set_color('r')
ax.spines['bottom'].set_color('y')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.annotate('y=sin(x)',xy=(2.5,0.6),xytext=(3.5,0.6),arrowprops=dict(arrowstyle='->',facecolor='black'))
ax.text(-2.1,0.65,'y=cos(x)',color='b',bbox=dict(facecolor='black',alpha=0.2))

plt.title('余弦函数在[-5,5]的图像',family='STXINWEI',size=20,color='b',loc='right')
cosine,=ax.plot(x,y)
sine,=ax.plot(x,y1)
plt.legend([sine,cosine],elements,loc='best')
ax.grid(ls=':',lw=0.8,color='b')
ax.plot(x,y,lw=2)
plt.show()

使用Matplotlib美化和修饰图形

4. 使用颜色

4.1 使用颜色参数

颜色参数传入色彩值有3种方法

(1)使用色彩的英文单词,其中常用颜色可以使用单字母缩写

(2)使用16进制RGB字符串,不用区分大小写,如#8e3e1f表示栗色

(3)使用RGB或RGBA数字元组,表示每一个元素的取值范围为0~1,如(0.6,0.3,0.7,0.8)

以下代码选取了上述颜色中的6种来绘制直线

import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax=fig.add_subplot(111)
colors=['k','lightgreen','skyblue','#8e3e1f','#f2eada',(0.6,0.3,0.7,0.8)]
x=np.arange(3,13,1)
y=np.linspace(1,1,10)
for i,color in enumerate(colors):
    ax.text(0,i+0.2,"{}".format(color),family='Arial',color='b',size=8)
    ax.plot(x,(i+0.2)*y,ls='-',color=color,lw=6)
    print(x)
    print((i+0.2)*y)
ax.set_xlim(-1,12)
ax.set_ylim(0,5.5)
ax.set_xticks([])
ax.set_yticks([])
plt.show()

使用Matplotlib美化和修饰图形

4.2 使用色彩映射和颜色标尺

色彩映射是将不同亮度映射到不同色彩的操作,使用色彩映射可以冲哦那个新调整图像,使其在新的色彩空间中显示。可以在image(),pcolor()和scatter()等函数上使用色彩映射。

常用的色彩映射分为以下三类:

  1. Sequential:同一颜色从低饱和度过度到高饱和度的单色色彩映射,如Greys,Oranges,PuBuGn,autumn,winter等
  2. Diverging:从中间的明亮颜色过渡到两个不同颜色范围的方向上,如PiYG,RdYlBu,Spectral等
  3. Qualitative:颜色反差大,便于不同种类数据的直观区分,如Accent,Paired等

所有的色彩映射都可以同伙增加后缀"_r"来获取反向色彩映射

以下分别对示例图片应用了winter,RdYlBu和Accent这3种色彩映射,首先来看原图

import scipy.misc
import matplotlib.pyplot as plt
plt.imshow(scipy.misc.ascent())
plt.show()

使用Matplotlib美化和修饰图形

应用winter色彩映射 如下

import scipy.misc
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.imshow(scipy.misc.ascent(),cmap=mpl.cm.winter)
plt.show()

使用Matplotlib美化和修饰图形

应用RdYlBu色彩映射 代码如下:

import scipy.misc
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.imshow(scipy.misc.ascent(),cmap=mpl.cm.RdYlBu)
plt.show()

使用Matplotlib美化和修饰图形

应用Accent色彩映射 代码如下:

import scipy.misc
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.imshow(scipy.misc.ascent(),cmap=mpl.cm.Accent)
plt.show()

使用Matplotlib美化和修饰图形

通过使用色彩映射,可以为图像添加颜色标尺,以下代码使用colorbar()函数为应用了灰度映射的示例图片添加了颜色标尺

import scipy.misc
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.imshow(scipy.misc.ascent(),cmap=mpl.cm.Accent)
plt.colorbar()
plt.show()

使用Matplotlib美化和修饰图形

5.划分画布

画布是绘制和显示图形的区域。将画布划分为多个子区域的目的是为了更好地利用画布的空间,在一个画布上绘制多个图形,从而提高查看效率。

[En]

The canvas is the area where graphics are drawn and displayed. The purpose of dividing the canvas into several sub-areas is to make better use of the space of the canvas and to draw multiple graphics in one canvas so as to improve the viewing efficiency.

subplots()函数用于将画布划分为网格状的若干子区,其原型如下:

subplots(nrows,ncols,**kwargs)

参数含义:nrows:网格行数 ncols:网格列数

也可使用subplot()函数直接定位到划分后的子区,其原型如下

subplot(nrows,ncols,index,**kwargs)

参数含义:index:划分后子区的序号,子区序号按子区在画布中位置从左到右,从上到下的顺序,从1开始递增。例如subplot(2,3,4)表示第2行第1个子区(总第4个)

import scipy.misc
import matplotlib as mpl
import matplotlib.pyplot as plt
fig,ax=plt.subplots(2,2)
ax[0,0].imshow(scipy.misc.ascent())
ax[0,1].imshow(scipy.misc.ascent(),cmap=mpl.cm.Accent)
ax[1,0].imshow(scipy.misc.ascent(),cmap=mpl.cm.winter)
ax[1,1].imshow(scipy.misc.ascent(),cmap=mpl.cm.RdYlBu)
plt.show()

使用Matplotlib美化和修饰图形

以上就是Matplotlib的美化和修饰图形 感谢大家的收藏和点赞 !!

如有问题在可下面评论一起讨论!!

Original: https://blog.csdn.net/iwantoseeu/article/details/122249699
Author: 要不要长胖_
Title: 使用Matplotlib美化和修饰图形



相关阅读

Title: Tensorflow 2.9.1安装笔记

CPU:i7-4790k

显卡:GTX2060

Cuda 版本:11.3

Cunn版本: 11.6

Python版本:3.7.7

不想用anacoda,直接装 tensorflow

1.准备工作

  • 安装python3.7.7(之前安装好的)

可以根据需要安装相应的版本,不建议安装最新版,python版本之间的代码兼容度不好。3.6~3.8可能比较合适。

我安装的是11.3版本。

deviceQuery.exe 和 bandwithTest.exe测试通过。

  • 下载Tensorflow

我下载的是 tensorflow-2.9.1-cp37-cp37m-win_amd64.whl

  • 安装组件

安装Tensorflow之前,安装好以下支持模块

A.Numpy: pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple

B.mkl: pip install mkl -i https://pypi.tuna.tsinghua.edu.cn/simple

C.protobuf pip install protobuf -i https://pypi.tuna.tsinghua.edu.cn/simple

2.安装Tensorflow

把 tensorflow-2.9.1-cp37-cp37m-win_amd64.whl 放到d盘根目录,打开命令行并转到D:\

pip install tensorflow-2.9.1-cp37-cp37m-win_amd64.whl -i https://pypi.tuna.tsinghua.edu.cn/simple

这样在安装过程中加载其他模块的时候,速度会非常快。

3.测试

import tensorflow as tf
print("Tensorflow version:")
print(tf.__version__)

print("CPU/GPU devices for Tensorflow:")
gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
cpus = tf.config.experimental.list_physical_devices(device_type='CPU')
print(gpus)
print(cpus)

运行结果:

Tensorflow version:
2.9.1
CPU/GPU devices for Tensorflow:
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
[PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU')]

至此安装完毕。

IDE可以使用Visual Studio Code(小规模测试)

或者Pycharm(程序较大很方便)

Original: https://blog.csdn.net/st01lsp/article/details/125294794
Author: st01lsp
Title: Tensorflow 2.9.1安装笔记

相关文章
3D卷积神经网络详解 人工智能

3D卷积神经网络详解

1 3d卷积的官方详解 2 2D卷积与3D卷积 1)2D卷积 2D卷积:卷积核在输入图像的二维空间进行滑窗操作。 2D单通道卷积 对于2维卷积,一个3*3的卷积核,在单通道图像上进行卷积,得到输出的动...
基于python的图像识别 人工智能

基于python的图像识别

基于python的图像识别 图像识别364 图像识别391 这里图像识别,涉及到python3.9.1和python3.6.4。 之所以着重提及python版本,是因为代码使用了tensorflow。...
deeplab-v3+原理详解 人工智能

deeplab-v3+原理详解

入门小菜鸟,希望像做笔记记录自己学的东西,也希望能帮助到同样入门的人,更希望大佬们帮忙纠错啦~侵权立删。 目录 一、deeplab-v3+提出原因与简单介绍 二、deeplab-v3+网络结构图 三、...
目标检测 YOLOv5 使用入门 人工智能

目标检测 YOLOv5 使用入门

目标检测 YOLOv5 使用入门 1. 源码准备 2. 例子 3. 运行 源码准备 在很早之前,在 《深度学习笔记(40) YOLO》 提及到 YOLO 目标检测 目前已经出到了 YOLOv5,源码放...