matploblib基本图形

matploblib基本图形

基本操作,更详细的操作需要查手册。

柱形图

mp.bar(水平坐标, 高度, 宽度[, 底坐标], color=颜色,
alpha=透明度, label=图例标签)

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
apples = np.array([
    30, 25, 22, 36, 21, 29, 20, 24, 33, 19, 27, 15])
oranges = np.array([
    24, 33, 19, 27, 35, 20, 15, 27, 20, 32, 20, 22])
mp.figure('Bar', facecolor='lightgray')
mp.title('Bar', fontsize=20)
mp.xlabel('Month', fontsize=14)
mp.ylabel('Price', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(axis='y', linestyle=':')
mp.ylim((0, 40))
x = np.arange(len(apples))
mp.bar(x, apples, 0.4, color='dodgerblue',
       label='Apple')
mp.bar(x + 0.4, oranges, 0.4, color='orangered',
       label='Orange', alpha=0.75)
mp.xticks(x +0.2, [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])
mp.legend()
mp.show()

在这里插入图片描述

饼图

mp.pie(值, 间隙, 标签, 颜色, 格式,
shadow=是否带阴影, startangel=起始角度)

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
values = [26, 17, 21, 29, 11]
spaces = [0.05, 0.01, 0.01, 0.01, 0.01]
labels = ['Python', 'JavaScript',
          'C++', 'Java', 'PHP']
colors = ['dodgerblue', 'orangered',
          'limegreen', 'violet', 'gold']
mp.figure('Pie', facecolor='lightgray')
mp.title('Pie', fontsize=20)
mp.pie(values, spaces, labels, colors, '%d%%',
       shadow=True, startangle=90)
# 等轴比例
mp.axis('equal')
mp.show()

在这里插入图片描述

热力图处理

用图形的方式显示矩阵,每一个像素就是一个点
1 2 3
4 5 6
7 8 9
mp.imshow(矩阵, cmap=颜色映射, origin=纵轴方向)
/ hight: 缺省,原点在左上角
origin \ low: 原点在左下角

例:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
n = 1000
# 网格化
x, y = np.meshgrid(np.linspace(-3, 3, n),
                   np.linspace(-3, 3, n))
z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(
    -x ** 2 - y ** 2)
mp.figure('Hot', facecolor='lightgray')
mp.title('Hot', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
# 绘制热成像图
mp.imshow(z, cmap='jet', origin='low') #cmap具体参数需要查表。。。
mp.colorbar().set_label('z', fontsize=14)
mp.show()

灰度处理

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import scipy.misc as sm
import matplotlib.pyplot as mp
#读取图片并将其转换为矩阵
image = sm.imread(r"C:\Users\Cs\Desktop\删除\补货.png", True).astype(np.uint8)
mp.figure('Image', facecolor='lightgray')
mp.title('Lily', fontsize=20)
mp.axis('off')  # 关闭坐标轴
mp.imshow(image, cmap='gray')
mp.show()

曲面图

曲面表面
ax.plot_surface(点阵X坐标矩阵, 点阵Y坐标矩阵, 点阵Z坐标矩阵,rstride=行跨距, cstride=列跨距, cmap=颜色映射)
曲面线框
ax.plot_wireframe(点阵X坐标矩阵, 点阵Y坐标矩阵, 点阵Z坐标矩阵,rstride=行跨距, cstride=列跨距, linewidth=线宽, color=颜色)

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d
# 生成数据
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n),
                   np.linspace(-3, 3, n))
z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(
    -x ** 2 - y ** 2)
# 创建图形窗口
mp.figure('3D Wireframe')
# 创建三维坐标系
ax = mp.gca(projection='3d')
# 设置窗口标题
mp.title('3D Wireframe', fontsize=20)
# 设置坐标轴标签
ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_zlabel('z', fontsize=14)
# 设置刻度参数
mp.tick_params(labelsize=10)
# 绘制三维线框图
ax.plot_wireframe(
    x, y, z, rstride=30, cstride=30,
    linewidth=0.5, color='dodgerblue')
# 创建图形窗口
mp.figure('3D Surface')
# 创建三维坐标系
ax = mp.gca(projection='3d')
# 设置窗口标题
mp.title('3D Surface', fontsize=20)
# 设置坐标轴标签
ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_zlabel('z', fontsize=14)
# 设置刻度参数
mp.tick_params(labelsize=10)
# 绘制三维表面图
ax.plot_surface(
    x, y, z, rstride=10, cstride=10, cmap='jet')
# 显示图形
mp.show()

三维散点图

ax.scatter(X坐标, Y坐标, Z坐标, s=大小, marker=点形, edgecolor=边缘色, facecolor=填充色, zorder=Z顺序)

import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d
n = 1000
#正态分布的随机数
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
z = np.random.normal(0, 1, n)
d = np.sqrt(x ** 2 + y ** 2 + z ** 2)
mp.figure('3D Scatter')
ax = mp.gca(projection='3d')  # 创建三维坐标系
mp.title('3D Scatter', fontsize=20)
ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_zlabel('z', fontsize=14)
mp.tick_params(labelsize=10)
ax.scatter(x, y, z, s=60, c=d, cmap='jet_r',alpha=0.5)
mp.show()

动画初探

动画真的卡
动画这一块比较模糊,不是很理解。
import matplotlib.animation as ma
def 更新回调函数(序列号):
更新画面显示

ma.FuncAnimation(图像窗口, 更新回调函数,
interval=时间间隔(毫秒))

ma.FuncAnimation(图像窗口, 更新回调函数, 生成器函数, interval=时间间隔(毫秒))
每经过一个"时间间隔",“更新回调函数"会被matplotlib调用一次,matplotlib先调用"生成器函数”,用"生成器函数"产生(yeild)的值作为参数调用"更新回调函数"。
回调函数生成原理
matplotlib:

while True:
延时interval毫秒
生成值 = 生成器函数()
更新回调函数(生成值)

import matplotlib.pyplot as mp
import numpy as np
import matplotlib.animation as ma
#生成100个气泡
n_bubbles=100
#每个气泡生成一个类型,具体需要查手册
bubbles=np.zeros(n_bubbles,dtype=[
    ('position',float,2),
    ('size',float),
    ('growth',float,1),
    ('color',float,4)])
bubbles['position']=np.random.uniform(0,1,(n_bubbles,2))#生成一个n_bubbles,2阵列的随机数,uniform为均匀分布,0,1为取值范围,
bubbles['size']=np.random.uniform(50,750,n_bubbles)
bubbles['growth']=np.random.uniform(30,150,n_bubbles)
bubbles['color']=np.random.uniform(0,1,(n_bubbles,4))
mp.figure("bubbles",facecolor='lightgray')
mp.xticks(())
mp.yticks(())
#散点图
sc=mp.scatter(bubbles['position'][:,0],bubbles['position'][:,1],c=bubbles['color'],s=bubbles['size'])
def update(number):
    #更新各点位数据
    bubbles['size'] += bubbles['growth']
    # burst=number % n_bubbles
    burst=int(np.random.uniform(0,n_bubbles))
    bubbles['position'][burst]=np.random.uniform(0,1,2)
    bubbles['size'][burst]=0
    bubbles['growth'][burst]=np.random.uniform(30,150)
    bubbles['color'][burst]=np.random.uniform(0,1,4)
    #将更新的数据重新画出来
    sc.set_offsets(bubbles['position'])
    sc.set_sizes(bubbles['size'])
    sc.set_facecolor(bubbles['color'])

anim=ma.FuncAnimation(mp.gcf(),update,interval=10)
mp.show()

在这里插入图片描述
心电图示例:

import numpy as np
import matplotlib.pyplot as mp
import matplotlib.animation as ma
mp.figure('Signal', facecolor='lightgray')
mp.title('Signal', fontsize=20)
mp.xlabel('Time', fontsize=14)
mp.ylabel('Signal', fontsize=14)
ax = mp.gca()
ax.set_ylim(-3, 3)
ax.set_xlim(0, 10)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
# 创建曲线对象
pl = mp.plot([], [], c='orangered')[0]
# 在曲线对象内部创建缓冲区,以容纳曲线上点的横纵坐标
pl.set_data([], [])

# 更新回调函数
def update(data):
    t, v = data
    # 获取曲线上当前所有的点
    x, y = pl.get_data()
    # 追加新采集到的点
    x.append(t)
    y.append(v)
    # 获取当前水平坐标范围
    x_min, x_max = ax.get_xlim()
    # 如果新点的水平坐标超过水平坐标范围
    if t >= x_max:
        # 重新设置水平坐标范围
        ax.set_xlim(t - (x_max - x_min), t)
        # 重新绘制坐标轴
        ax.figure.canvas.draw()
    # 设置曲线上的点
    pl.set_data(x, y)


# 生成器函数
def generator():
    t = 0
    while True:
        v = np.sin(2 * np.pi * t) * np.exp(
            np.sin(0.2 * np.pi * t))
        yield t, v
        t += 0.05


# 启动动画
anim = ma.FuncAnimation(
    mp.gcf(), update, generator, interval=5)
mp.show()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_36179862/article/details/84830722
今日推荐