• 『Python』matplotlib坐标轴应用


    1. 设置坐标轴的位置和展示形式

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    mpl.use('Qt5Agg')
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    mpl.rcParams['font.serif'] = ['SimHei']
    mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题,或者转换负号为字符串
    
    plt.axes([0.05, 0.7, 0.3, 0.3], frameon=True, facecolor="y", aspect="equal")
    plt.plot(np.arange(3), [0, 1, 0], color="blue", linewidth=2, linestyle="--")
    plt.ylim(0, 1.5)
    plt.axis("image")
    
    plt.axes([0.3, 0.4, 0.3, 0.3], frameon=True, facecolor="y", aspect="equal")
    plt.plot(2 + np.arange(3), [0, 1, 0], color="blue", linewidth=2, linestyle="-")
    plt.ylim(0, 15)
    plt.axis([2.1, 3.9, 0.5, 1.9])
    
    plt.axes([0.55, 0.1, 0.3, 0.3], frameon=True, facecolor="y", aspect="equal")
    plt.plot(4 + np.arange(3), [0, 1, 0], color="blue", linewidth=2, linestyle=":")
    plt.ylim(0, 1.5)
    plt.axis("off")
    
    plt.show()
    
    • 函数axes(rect, frameon=True, facecolor="y")

      • rect = [left, bottom, width, height]

        leftbottom分别表示坐标轴的左侧边缘和底部边缘距离画布边缘的距离,widthheight分别表示坐标轴的宽度和高度
        leftwidth是画布宽度归一化后的距离,bottomheight是画布高度归一化后的距离。

      • frameon=True
        是否显示四条轴脊

      • facecolor="y"
        填充坐标轴背景的颜色

    • 函数axis()

      • [xmin, xmax, ymin, ymax]
        显示坐标轴的范围
      • option,可取值为
        • 'on':打开坐标轴
        • 'off':关闭坐标轴显示
        • 'equal':设置相等的比例,y轴和x轴单位刻度对应长度是一样的
        • 'scaled':通过更改绘图框的尺寸设置相等的缩放比例
        • 'tight':设置足够大的限制来显示所有数据
        • 'auto':自动确定
        • 'image':‘scaled’ with axis limits equal to data limits
        • 'square':方形图,类似于 ‘scaled’,但是强制xmax-xmin = ymax-ymin

    2. 坐标轴刻度的显示

    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    mpl.rcParams['font.serif'] = ['SimHei']
    mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题,或者转换负号为字符串
    
    ax1 = plt.subplot(121)
    ax1.set_xticks(range(0, 251, 50))
    plt.grid(True, axis="x")
    
    ax2 = plt.subplot(122)
    ax2.set_xticks([])
    plt.grid(True, axis="x")
    
    plt.show()
    
    

    如果不设置坐标轴刻度,则网格线也不会被设置。设置刻度还包括刻度标签,可以用函数Axes.set_xticklabels()Axes.set_yticklabels()设置对应刻度线的标签

    3. 坐标轴的样式和位置的定制化展示

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    from matplotlib.ticker import FormatStrFormatter
    from calendar import day_name
    
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    mpl.rcParams['font.serif'] = ['SimHei']
    mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题,或者转换负号为字符串
    
    fig = plt.figure()
    
    ax = fig.add_axes([0.2, 0.2, 0.7, 0.7])
    ax.spines["bottom"].set_position(("outward", 10))
    ax.spines["left"].set_position(("outward", 10))
    ax.spines["top"].set_color("none")
    ax.spines["right"].set_color("none")
    
    x = np.arange(1, 8, 1)
    y = 2 * x + 1
    
    ax.scatter(x, y, c="orange", s=50, edgecolors="orange")
    
    for tickline in ax.xaxis.get_ticklines():
        tickline.set_color("blue")
        tickline.set_markersize(8)
        tickline.set_markeredgewidth(5)
    
    for ticklabel in ax.get_xmajorticklabels():
        ticklabel.set_color("slateblue")
        ticklabel.set_fontsize(12)
        ticklabel.set_rotation(20)
    
    ax.yaxis.set_major_formatter(FormatStrFormatter(f"$yen%1.1f$"))
    plt.xticks(x, day_name[0:7], rotation=20)
    ax.yaxis.set_ticks_position("left")
    ax.xaxis.set_ticks_position("bottom")
    
    for tickline in ax.yaxis.get_ticklines():
        tickline.set_color("lightgreen")
        tickline.set_markersize(8)
        tickline.set_markeredgewidth(5)
    
    for ticklabel in ax.get_ymajorticklabels():
        ticklabel.set_color("green")
        ticklabel.set_fontsize(15)
    
    ax.grid(ls=":", lw=1, color="gray", alpha=0.5)
    
    plt.show()
    

    4. 移动坐标轴的位置

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    mpl.rcParams['font.serif'] = ['SimHei']
    mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题,或者转换负号为字符串
    
    x = np.linspace(-2 * np.pi, 2 * np.pi, 200)
    y = np.sin(x)
    y1 = np.cos(x)
    
    ax = plt.subplot(111)
    
    ax.plot(x, y, ls="-", lw=2, label=r"$sin(x)$")
    ax.plot(x, y1, ls="-", lw=2, label=r"$cos(x)$")
    
    ax.legend(loc="lower left")
    
    plt.title(r"$sin(x)$" + "和" + r"$cos(x)$" + "函数")
    
    ax.set_xlim(-2 * np.pi, 2 * np.pi)
    
    plt.xticks([-2 * np.pi, -3 * np.pi / 2, -1 * np.pi, -1 * np.pi / 2,
                0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi],
               [r"$-2pi$", r"$-3pi/2$", r"$-pi$", r"$-pi/2$",
                r"$0$", r"$pi/2$", r"$pi$", r"$3pi/3$", r"$2pi$"]
               )
    
    ax.spines["right"].set_color("none")
    ax.spines["top"].set_color("none")
    
    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")
    
    plt.show()
    

    ax.spines[key]会调用轴脊字典,如bottomtoprightleft键值是对应位置轴脊,ax.spines["bottom"].set_position(("data", 0))表示将底轴移到数轴0坐标位置

  • 相关阅读:
    HTML
    JavaScript-DOM
    Visual Studio Usage
    Char 05 使用提供程序
    Char 04 运行命令
    Char 03 使用帮助系统
    char 02 初识 Powershell
    Char 01 PowerShell
    Linux Nginx
    Linux SSLH
  • 原文地址:https://www.cnblogs.com/ice-coder/p/12897529.html
Copyright © 2020-2023  润新知