其他分享
首页 > 其他分享> > matplotlib数据可视化

matplotlib数据可视化

作者:互联网

matplotlib数据可视化

1. matplotlib简单介绍

绘制图像一共有两种方式,一种是面向对象的(显示的),利用Figure,axes,另一个是直接用plot.plt(隐式的)

1. 图像的组成

  1. Figure,顶层级,用来容纳所有绘图元素
  2. Axes,容纳大量元素可以用来构造一幅幅子图(一个figure可以由一个或多个子图组成)
  3. Axis,axes的下属层级,用来处理所有和坐标轴,网格有关的元素
  4. Tick,axis的下属层级,用来处理所有和刻度有关的元素

在这里插入图片描述

2.matplot的底层结构

1. 三个层次API:

matplotlib.backend_bases.FigureCanvas 代表了绘图区,所有的图像都是在绘图区完成的
matplotlib.backend_bases.Renderer 代表了渲染器,可以近似理解为画笔,控制如何在 FigureCanvas 上画图。
matplotlib.artist.Artist 代表了具体的图表组件,即调用了Renderer的接口在Canvas上作图。

2. Artist分类

1. primitive

  1. 包含一些用在绘图区的标准图像对象,例如:曲线Line2D,文字text,矩形Rectangle,图像image等

    2. containers

  2. 用来装基本要素的地方,包括图形figure,坐标系Axes,坐标轴Axis

在这里插入图片描述

2. matplotlib标准用法

import matplotlib.pyplot as plt
import numpy as np

#step1
fig = plt.figure()

#step2
ax = fig.add_subplot(2,1,1)

#step3
t = np.arange(0.0,1.0,.01)
s = np.sin(2 * np.pi * t)
line, = ax.plot(t,s,color='blue',lw=2)

3. primitives详细介绍

1. 2DLine:

连接所有顶点的实现样式,也可以是每个顶点的标记

1. 常用参数:

xdata,ydata,linewidth,linestyle,color,marker,markersize

2. 设置属性的方法:
  1. plot()中设置
# 1) 直接在plot()函数中设置
import matplotlib.pyplot as plt
x = range(0,5)
y = [2,5,7,8,10]
plt.plot(x,y, linewidth=10) # 设置线的粗细参数为10
  1. 获得线对象,对线对象进行设置
# 2) 通过获得线对象,对线对象进行设置
x = range(0,5)
y = [2,5,7,8,10]
line, = plt.plot(x, y, '-')
line.set_antialiased(False) # 关闭抗锯齿功能
  1. 获得线属性,使用setp()设置
# 3) 获得线属性,使用setp()函数设置
x = range(0,5)
y = [2,5,7,8,10]
lines = plt.plot(x, y)
plt.setp(lines, color='r', linewidth=10)
3. 绘制lines
  1. 绘制直线lines

  2. pyplot方法绘制

# 1. pyplot方法绘制
import matplotlib.pyplot as plt
x = range(0,5)
y = [2,5,7,8,10]
plt.plot(x,y)
  1. Line2D对象绘制
# 2. Line2D对象绘制
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D      

fig = plt.figure()
ax = fig.add_subplot(111)
line = Line2D(x, y)
ax.add_line(line)
ax.set_xlim(min(x), max(x))
ax.set_ylim(min(y), max(y))

plt.show()
  1. errorbar绘制误差折线图

  2. 构造函数主要参数:

x,y,yerr(y轴水平的误差),xerr,fmt(折线图的风格),ecolor,elinewidth

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
x = np.arange(10)
y = 2.5 * np.sin(x / 20 * np.pi)
yerr = np.linspace(0.05, 0.2, 10)
plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)')
2. patches
1. Rectangle矩形:

通过锚点xy及其宽高生成

  1. hist-直方图

    1. 常用参数:

      x,bins,range,density(显示频数统计结果),histtype(bar,barstacked,setp,setpfilled),align(对齐方式,left,mid,right),log(True,表示指数刻度),stacked(True,表示堆积状图)

import matplotlib.pyplot as plt
import numpy as np 
x=np.random.randint(0,100,100) #生成[0-100)之间的100个数据,即 数据集 
bins=np.arange(0,101,10) #设置连续的边界值,即直方图的分布区间[0,10),[10,20)... 
plt.hist(x,bins,color='fuchsia',alpha=0.5)#alpha设置透明度,0为完全透明 
plt.xlabel('scores') 
plt.ylabel('count') 
plt.xlim(0,100)#设置x轴分布范围 plt.show()
  1. bar-柱状图

    1. 常用参数:

      left,height,alpha,width,color或facecolor,edgecolor,label

# bar绘制柱状图
import matplotlib.pyplot as plt
y = range(1,17)
plt.bar(np.arange(16), y, alpha=0.5, width=0.5, color='yellow', edgecolor='red', label='The First Bar', lw=3)
# Rectangle矩形类绘制柱状图
#import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)

for i in range(1,17):
rect =  plt.Rectangle((i+0.25,0),0.5,i)#Rectangle xy表示左下点
ax1.add_patch(rect)
ax1.set_xlim(0, 16)
ax1.set_ylim(0, 16)
plt.show()
2. Ploygon-多边形
# 用fill来绘制图形
import matplotlib.pyplot as plt
x = np.linspace(0, 5 * np.pi, 1000) 
y1 = np.sin(x)
y2 = np.sin(2 * x) 
plt.fill(x, y1, color = "g", alpha = 0.3)#xy是一个N×2的numpy array,为多边形的顶点
3. Wedge-楔形

理解:是以坐标x,y为中心,半径为r,从θ1扫到θ2(单位是度),如果宽度给定,则从内半径r -宽度到外半径r画出部分楔形

  1. pie-饼状图
import matplotlib.pyplot as plt 
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10] #契型的形状,一维数组
explode = (0, 0.1, 0, 0) #它指定用于偏移每个楔形块的半径的分数
fig1, ax1 = plt.subplots() 
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) #label 用于指定每个契型块的标记,取值是列表或为None 
#autopct 
#startangle 饼状图开始的绘制的角度
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. 
plt.show()

3. collections

  1. collections类是用来绘制一组对象的集合。
  2. 主要参数:
# 用scatter绘制散点图
x = [0,2,4,6,8,10] 
y = [10]*len(x) 
s = [20*2**n for n in range(len(x))] #尺寸大小
plt.scatter(x,y,s=s) 
plt.show()

4. images

  1. 绘制image图像的类,其中最常用的imshow可以根据数组绘制成图像
import matplotlib.pyplot as plt
import numpy as np
methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16',
'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric',
'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']


grid = np.random.rand(4, 4)

fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6),
subplot_kw={'xticks': [], 'yticks': []})

for ax, interp_method in zip(axs.flat, methods):
ax.imshow(grid, interpolation=interp_method, cmap='viridis')
ax.set_title(str(interp_method))

plt.tight_layout()
plt.show()

3. 对象容器-Object container

1. Figure容器

matplotlib.figure.FigureArtist最顶层的container对象容器,它包含了图表中的所有元素。

一张图表的背景就是在Figure.patch的一个矩阵Rectangle,当我们向图表添加Figure.add_subplot()或者Figure.add_axes(),这些都会添加到Figure.axes中

fig = plt.figure()
ax1 = fig.add_subplot(211) # 作一幅2*1的图,选择第1个子图
ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.3]) # 位置参数,四个数分别代表了(left,bottom,width,height)
print(ax1) 
print(fig.axes) # fig.axes 中包含了subplot和axes两个实例, 刚刚添加的
fig = plt.figure()
ax1 = fig.add_subplot(211)
for ax in fig.axes:#通过遍历axes来修改ax
    ax.grid(True)

Figure容器的常见属性:
Figure.patch属性:Figure的背景矩形
Figure.axes属性:一个Axes实例的列表(包括Subplot)
Figure.images属性:一个FigureImages patch列表
Figure.lines属性:一个Line2D实例的列表(很少使用)
Figure.legends属性:一个Figure Legend实例列表(不同于Axes.legends)
Figure.texts属性:一个Figure Text实例列表

2. Axes容器

Axes包含了一个patch属性,对于笛卡尔坐标系而言,它是一个Rectangle;对于极坐标而言,它是一个Circle。这个patch属性决定了绘图区域的形状、背景和边框。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

fig = plt.figure()
ax = fig.add_subplot(111)
rect = ax.patch  # axes的patch是一个Rectangle实例
rect.set_facecolor('green')

3. Axis容器

tick linegrid linetick label以及axis label的绘制,它包括坐标轴上的刻度线、刻度label、坐标网格、坐标轴标题。通常你可以独立的配置y轴的左边刻度以及右边的刻度,也可以独立地配置x轴的上边刻度以及下边的刻度。

# 不用print,直接显示结果
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

fig, ax = plt.subplots()
x = range(0,5)
y = [2,5,7,8,10]
plt.plot(x, y, '-')

axis = ax.xaxis # axis为X轴对象
axis.get_ticklocs()     # 获取刻度线位置
axis.get_ticklabels()   # 获取刻度label列表(一个Text实例的列表)。 可以通过minor=True|False关键字参数控制输出minor还是major的tick label。
axis.get_ticklines()    # 获取刻度线列表(一个Line2D实例的列表)。 可以通过minor=True|False关键字参数控制输出minor还是major的tick line。
axis.get_data_interval()# 获取轴刻度间隔
axis.get_view_interval()# 获取轴视角(位置)的间隔
fig = plt.figure() # 创建一个新图表
rect = fig.patch   # 矩形实例并将其设为黄色
rect.set_facecolor('lightgoldenrodyellow')

ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4]) # 创一个axes对象,从(0.1,0.3)的位置开始,宽和高都为0.4,
rect = ax1.patch   # ax1的矩形设为灰色
rect.set_facecolor('lightslategray')


for label in ax1.xaxis.get_ticklabels(): 
    # 调用x轴刻度标签实例,是一个text实例
    label.set_color('red') # 颜色
    label.set_rotation(45) # 旋转角度
    label.set_fontsize(16) # 字体大小

for line in ax1.yaxis.get_ticklines():
    # 调用y轴刻度线条实例, 是一个Line2D实例
    line.set_color('green')    # 颜色
    line.set_markersize(25)    # marker大小
    line.set_markeredgewidth(2)# marker粗细

plt.show()

4. Tick容器

matplotlib.axis.Tick是从FigureAxesAxisTick中最末端的容器对象。
Tick包含了tickgrid line实例以及对应的label

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))

# 设置ticker的显示格式
formatter = matplotlib.ticker.FormatStrFormatter('$%1.2f')
ax.yaxis.set_major_formatter(formatter)

# 设置ticker的参数,右侧为主轴,颜色为绿色
ax.yaxis.set_tick_params(which='major', labelcolor='green',
                         labelleft=False, labelright=True)

plt.show()

3. 布局格式

1. 子图

1. 使用plt.subplots绘制均匀状态下的子图

fig, axs = plt.subplots(2, 5, figsize=(10, 4), sharex=True, sharey=True)
#figsize 参数可以指定整个画布的大小
#sharex 和 sharey 分别表示是否共享横轴和纵轴刻度
#tight_layout 函数可以调整子图的相对大小使字符不会重叠
fig.suptitle('样例1', size=20)
for i in range(2):
    for j in range(5):
        axs[i][j].scatter(np.random.randn(10), np.random.randn(10))
        axs[i][j].set_title('第%d行,第%d列'%(i+1,j+1))
        axs[i][j].set_xlim(-5,5)
        axs[i][j].set_ylim(-5,5)
        if i==1: axs[i][j].set_xlabel('横坐标')
        if j==0: axs[i][j].set_ylabel('纵坐标')
fig.tight_layout()
N = 150
r = 2 * np.random.rand(N)
theta = 2 * np.pi * np.random.rand(N)
area = 200 * r**2
colors = theta


plt.subplot(projection='polar')
plt.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75)

2. 使用GridSpec绘制非均匀子图

所谓非均匀包含两层含义,第一是指图的比例大小不同但没有跨行或跨列,第二是指图为跨列或跨行状态

fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows=2, ncols=5, width_ratios=[1,2,3,4,5], height_ratios=[1,3])
fig.suptitle('样例2', size=20)
for i in range(2):
    for j in range(5):
        ax = fig.add_subplot(spec[i, j])
        ax.scatter(np.random.randn(10), np.random.randn(10))
        ax.set_title('第%d行,第%d列'%(i+1,j+1))
        if i==1: ax.set_xlabel('横坐标')
        if j==0: ax.set_ylabel('纵坐标')
fig.tight_layout()
fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows=2, ncols=6, width_ratios=[2,2.5,3,1,1.5,2], height_ratios=[1,2])
fig.suptitle('样例3', size=20)
# sub1
ax = fig.add_subplot(spec[0, :3])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub2
ax = fig.add_subplot(spec[0, 3:5])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub3
ax = fig.add_subplot(spec[:, 5])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub4
ax = fig.add_subplot(spec[1, 0])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub5
ax = fig.add_subplot(spec[1, 1:5])
ax.scatter(np.random.randn(10), np.random.randn(10))
fig.tight_layout()

2. 子图上的方法

1. 在 ax 对象上定义了和 plt 类似的图形绘制函数

常用的有: plot, hist, scatter, bar, barh, pie

2. 常用直线的画法:

axhline, axvline, axline (水平、垂直、任意方向)

3. 用 grid 可以加灰色网格

4. 使用 set_xscale, set_title, set_xlabel

分别可以设置坐标轴的规度(指对数坐标等)、标题、轴名

5. legend, annotate, arrow, text 对象也可以进行相应的绘制

4.文字图例

1. Figure和Axes上的文本

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bBkKW9U6-1638780383886)(C:\Users\nabai\Documents\markdown图片\image-20210707200007404.png)]

1. text

2. title和set_title

3. figtext和text

4. suptitle

5. xlabel和ylabel

6. 字体的属性设置

7. 数学表达式

2. Tick上的文本

1. 简单模式

2. Tick Locators 和 Formatters

Tick Locators and Formatters完成对于刻度位置和刻度标签的设置

3. legend

5. 样式色彩

1. matplot的绘图样式

1. 预设的样式

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('default')
plt.plot([1,2,3,4],[2,3,4,5])
print(plt.style.available)
['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']

2. 自定义样式

在任意路径下创建一个后缀名为mplstyle的样式清单,编辑文件添加以下样式内容

axes.titlesize : 24
axes.labelsize : 20
lines.linewidth : 3
lines.markersize : 10
xtick.labelsize : 16
ytick.labelsize : 16

plt.style.use('file/presentation.mplstyle')
plt.plot([1,2,3,4],[2,3,4,5])

3. 设置rcparams

我们还可以通过修改默认rc设置的方式改变样式,所有rc设置都保存在一个叫做 matplotlib.rcParams的变量中。

mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.linestyle'] = '--'
plt.plot([1,2,3,4],[2,3,4,5])
mpl.rc('lines', linewidth=4, linestyle='-.')
plt.plot([1,2,3,4],[2,3,4,5])

4. 修改matplotlibrc文件

# 查找matplotlibrc文件的路径
mpl.matplotlib_fname()

2. matplotlib的色彩设置

1. RGB或RGBA

# 颜色用[0,1]之间的浮点数表示,四个分量按顺序分别为(red, green, blue, alpha),其中alpha透明度可省略
plt.plot([1,2,3],[4,5,6],color=(0.1, 0.2, 0.5))
plt.plot([4,5,6],[1,2,3],color=(0.1, 0.2, 0.5, 0.5))

2. HEX RGB 或 RGBA

3. 灰度色阶

4. 单字符基本颜色

5.颜色名称

6. 使用colormap设置一组颜色

参考链接:

fantastic matplotlib

标签:10,plt,matplotlib,可视化,fig,np,ax,数据
来源: https://blog.csdn.net/y1040468929/article/details/121750593