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数据分析 Matplotlib的常用操作 -> 正文阅读

[人工智能]Python数据分析 Matplotlib的常用操作

目录

1、简单的绘制图像

2、视图面板的常用操作

3、样式及各类常用修饰属性

4、legend图例的使用

5、添加文字等描述

6、不同类型图像的绘制


使用matplotlib需引入:

import matplotlib.pyplot as plt

通常2会配合着numpy使用,numpy引入:

import numpy as np

1、简单的绘制图像

def matplotlib_draw():
    # 从-1到1生成100个点,包括最后一个点,默认为不包括最后一个点
    x = np.linspace(-1, 1, 100, endpoint=True)

    y = 2 * x + 1
    plt.plot(x, y)  # plot将信息传入图中
    plt.show()  # 展示图片

2、视图面板的常用操作

def matplotlib_figure():
    x = np.linspace(-1, 1, 100)
    y1 = 2 * x + 1
    y2 = x ** 2  # 平方

    plt.figure()  # figure是视图面板
    plt.plot(x, y1)

    # 这里再创建一个视图面板,最后会生成两张图,figure只绘制范围以下的部分
    plt.figure(figsize=(4, 4))  # 设置视图长宽
    plt.plot(x, y2)

    plt.show()

3、样式及各类常用修饰属性

def matplotlib_style():
    x = np.linspace(-3, 3, 100)
    y1 = 2 * x + 1
    y2 = x ** 2  # 平方

    # 限制xy输出图像的范围
    plt.xlim((-1, 2))  # 限制x的范围
    plt.ylim((-2, 3))  # 限制y的范围

    # xy描述
    plt.xlabel('I am X')
    plt.ylabel('I am Y')

    # 设置xy刻度值
    # 从-2到2上取11个点,最后生成一个一维数组
    new_sticks = np.linspace(-2, 2, 11)
    plt.xticks(new_sticks)
    # 使用文字代替数字刻度
    plt.yticks([-1, 0, 1, 2, 3], ['level1', 'level2', 'level3', 'level4', 'level5'])

    # 获取坐标轴 gca get current axis
    ax = plt.gca()
    ax.spines['right'].set_color('red')  # 设置右边框为红色
    ax.spines['top'].set_color('none')  # 设置顶部边框为没有颜色,即无边框

    # 把x轴的刻度设置为'bottom'
    ax.xaxis.set_ticks_position('bottom')
    # 把y轴的刻度设置为'left'
    ax.yaxis.set_ticks_position('left')
    # 设置xy轴的位置,以下测试xy轴相交于(1,0)
    # bottom对应到0点
    ax.spines['bottom'].set_position(('data', 0))
    # left对应到1点
    ax.spines['left'].set_position(('data', 1))  # y轴会与1刻度对齐

    # 颜色、线宽、实线:'-',虚线:'--',alpha表示透明度
    plt.plot(x, y1, color="red", linewidth=1.0, linestyle='--', alpha=0.5)
    plt.plot(x, y2, color="blue", linewidth=5.0, linestyle='-')
    plt.show()  # 这里没有设置figure那么两个线图就会放到一个视图里

4、legend图例的使用

def matplotlib_legend():
    x = np.linspace(-3, 3, 100)
    y1 = 2 * x + 1
    y2 = x ** 2  # 平方

    l1, = plt.plot(x, y1, color="red", linewidth=1.0, linestyle='--', alpha=0.5)
    l2, = plt.plot(x, y2, color="blue", linewidth=5.0, linestyle='-')
    # handles里面传入要产生图例的关系线,labels中传入对应的名称,
    # loc='best'表示自动选择最好的位置放置图例
    plt.legend(handles=[l1, l2], labels=['test1', 'test2'], loc='best')
    plt.show()

5、添加文字等描述

def matplotlib_describe():
    x = np.linspace(-3, 3, 100)
    y = 2 * x + 1
    plt.plot(x, y, color="red", linewidth=1.0, linestyle='-')

    # 画点,s表示点的大小
    x0 = 0.5
    y0 = 2 * x0 + 1
    plt.scatter(x0, y0, s=50, color='b')

    # 画虚线,
    # k代表黑色,--代表虚线,lw线宽
    # 表示重(x0,y0)到(x0,-4)画线
    plt.plot([x0, x0], [y0, -4], 'k--', lw=2)
    # 标注,xytext:位置,textcoords设置起始位置,arrowprops设置箭头,connectionstyle设置弧度
    plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xytext=(+30, -30), 
                 textcoords="offset points", fontsize=16,
                 arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))

    # 文字描述
    plt.text(-3, 3, r'$this\ is\ the\ text$', fontdict={'size': '16', 'color': 'r'})

    plt.show()

6、不同类型图像的绘制

(1)scatter绘制散点图:

def matplotlib_scatter():
    plt.figure()
    plt.scatter(np.arange(5), np.arange(5))  # 安排两个0到4的数组绘制

    x = np.random.normal(0, 1, 500)  # 正态分布的500个数
    y = np.random.normal(0, 1, 500)

    plt.figure()
    plt.scatter(x, y, s=50, c='b', alpha=0.5)

    plt.show()

(2)bar绘制直方图:

def matplotlib_bar():
    x = np.arange(10)
    y = 2 ** x + 10
    # facecolor块的颜色,edgecolor块边框的颜色
    plt.bar(x, y, facecolor='#9999ff', edgecolor='white')
    # 设置数值位置
    for x, y in zip(x, y):  # zip将x和y结合在一起
        plt.text(x + 0.4, y, "%.2f" % y, ha='center', va='bottom')

    plt.show()

(3)contour轮廓图:

def matplotlib_contours():
    def f(a, b):
        return (1 - a / 2 + a ** 5 + b ** 3) * np.exp(-a ** 2 - b ** 2)

    x = np.linspace(-3, 3, 100)
    y = np.linspace(-3, 3, 100)

    X, Y = np.meshgrid(x, y)  # 将x和y传入一个网格中
    # 8表示条形线的数量,数量越多越密集
    plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)  # cmap代表图的颜色

    C = plt.contour(X, Y, f(X, Y), 8, color='black', linewidth=.5)
    plt.clabel(C, inline=True, fontsize=10)

    plt.xticks(())
    plt.yticks(())
    plt.show()

(4)3D图:

3D图绘制需额外再引入依赖:

from mpl_toolkits.mplot3d import Axes3D
def matplotlib_Axes3D():
    fig = plt.figure()  # 创建绘图面版环境
    ax = Axes3D(fig)  # 将环境配置进去

    x = np.arange(-4, 4, 0.25)
    y = np.arange(-4, 4, 0.25)
    X, Y = np.meshgrid(x, y)  
    R = np.sqrt(X ** 2 + Y ** 2)
    Z = np.sin(R)

    # stride控制色块大小
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
    ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap='rainbow')
    ax.set_zlim(-2, 2)

    plt.show()

(5)subplot子图绘制:

def matplotlib_subplot():
    plt.figure()  # 生成绘图面板
    plt.subplot(2, 1, 1)  # 两行1列绘图位置的第1个位置
    plt.plot([0, 1], [0, 1])  # 绘制从(0,0)绘制到(1,1)的图像
    plt.subplot(2, 3, 4)  # 两行3列绘图位置的第4个位置
    plt.plot([0, 1], [0, 1])  # 绘制从(0,0)绘制到(1,1)的图像
    plt.subplot(2, 3, 5)  # 两行3列绘图位置的第5个位置
    plt.plot([0, 1], [0, 1])  # 绘制从(0,0)绘制到(1,1)的图像
    plt.subplot(2, 3, 6)  # 两行3列绘图位置的第6个位置
    plt.plot([0, 1], [0, 1])  # 绘制从(0,0)绘制到(1,1)的图像

    plt.show()

(6)animation动图绘制

需额外导入依赖:

from matplotlib import animation
# ipython里运行可以看到动态效果
def matplotlib_animation():
    fig, ax = plt.subplots()

    x = np.arange(0, 2 * np.pi, 0.01)
    line, = ax.plot(x, np.sin(x))

    def animate(i):
        line.set_ydata(np.sin(x + i / 10))
        return line,

    def init():
        line.set_ydata(np.sin(x))
        return line,

    ani = animation.FuncAnimation(fig=fig, func=animate, init_func=init, interval=20)

    plt.show()

更多见官方文档:教程 | Matplotlib 中文

  人工智能 最新文章
2022吴恩达机器学习课程——第二课(神经网
第十五章 规则学习
FixMatch: Simplifying Semi-Supervised Le
数据挖掘Java——Kmeans算法的实现
大脑皮层的分割方法
【翻译】GPT-3是如何工作的
论文笔记:TEACHTEXT: CrossModal Generaliz
python从零学(六)
详解Python 3.x 导入(import)
【答读者问27】backtrader不支持最新版本的
上一篇文章      下一篇文章      查看所有文章
加:2022-01-04 13:26:12  更:2022-01-04 13:26:42 
 
开发: 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年5日历 -2024/5/18 22:48:20-

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