matplotlib学习总结

本文全面解析Matplotlib中各种绘图元素的名称与使用,包括图名、坐标轴标签、刻度、图例、背景网格等,以及如何通过代码进行自定义设置,帮助读者深入掌握Matplotlib绘图技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

经典matplotlib图

  • 学习matplotlib画图已经有一段时间了,各种操作都做了一遍,但是还是有点迷糊,尤其是坐标轴上各个部分的名称,在此特意将matplotlib上的经典例图的各部分名称全部总结在此,做个总结,以后再做操作上补充。

主要图像要素的名称

  • Title
    • 图名(在整个图的上面)
  • label
    • 标签(在坐标轴的边上)
    • 应用
      • 坐标轴标签自适应
        • fig.autofmt_xdate()
      • 设置y轴标签
        • ax1.set_ylabel(‘Y1’)
  • tick
    • 刻度
    • 设置坐标轴有多少格
      • ax.locator_params(‘x’, nbins = 10) # 设置x轴有10格组成
  • legend
    • 图例
    • 应用
      • plt.legend(loc = 0, ncol = 3) # 0代表最佳位置,3表示有三列
      • ax.legend()
  • grid
    • 背景网格
    • 应用
      • plt.grid(True)
      • ax.grid(True)
  • text
    • 文字注释(可以用TeX公式)
    • 应用
      • plt.text()
      • ax.text(2,4,r"$ \alpha_i \beta_j \pi \lambda \omega $", size = 25)
  • axis
    • 坐标轴
    • xmin, xmax, ymin, ymax = axis()
    • xmin, xmax, ymin, ymax = axis([xmin, xmax, ymin, ymax])
    • xmin, xmax, ymin, ymax = axis(option)
    • xmin, xmax, ymin, ymax = axis(**kwargs)
    • 参数可以为下列单词

============================================================

ValueDescription
‘on’Turn on axis lines and labels. Same as True.
‘off’Turn off axis lines and labels. Same as False.
‘equal’Set equal scaling (i.e., make circles circular) bychanging axis limits.
‘scaled’Set equal scaling (i.e., make circles circular) by changing dimensions of the plot box.
‘tight’Set limits just large enough to show all data.
‘auto’Automatic scaling (fill plot box with data).
‘normal’Same as ‘auto’; deprecated.
‘image’‘scaled’ with axis limits equal to data limits.
‘square’Square plot; similar to ‘scaled’, but initially forcing xmax-xmin = ymax-ymin

===========================================================

  • 应用

    • 可以自己定制坐标范围
      • plt.axis([-100,100,-10,200])
    • 单独调节某个参数
      • plt.xlim([-5,5])
    • 添加坐标轴
      • plt.twinx()
  • figure

    • 画板,是画纸的载体
    • https://www.zhihu.com/question/51745620

  • Axes/Subplot

    • 画纸 轴域 ~=子图

    • axes(轴域)可以理解一些轴的集合:axes不是数学上的座标轴,而是图形结构中的一个对象。所有绘图函数都是直接作用在当前axes对象上。

    • subplot子图就是画板上的画纸

    • 应用

      • plt.subplot(221)
      • fig = plt.figure()
      • fig.add_axes([0.1, 0.1, 0.8, 0.8])
      • fig.add_subplot(111)
    • https://www.zhihu.com/question/51745620(这里面还有作者对于面向对象和面向过程编程的思考和建议哦)

  • spines

    • 轴脊线-记录数据区域边界的线
    • gca
      • get current axes
    • 获取图像的轴,总共有四个轴top、bottom、left和right
    • plt.spines[‘top’]
    • plt.spines[‘top’].set_color()
      • plt.spines[‘right’].set_color(‘none’)(隐藏坐标轴)
    • plt.spines[‘top’].set_position()

主要函数的参数

  • color
    • 颜色
  • marker
    • 点型
    • linestyle
    • 线型
  • linewidth
    • 线宽
  • loc
    • 位置
  • ncol
  • nbins
    • 格数
  • size
    • 大小
  • family
    • 字体
  • style
    • 字体风格
  • bbox
    • 边框
  • alpha
    • 透明度
  • weight
    • 粗细
### Matplotlib 库使用教程 #### 安装 Matplotlib 要开始使用 Matplotlib,首先需要确保已正确安装该库。可以通过以下命令轻松完成安装: ```bash pip install matplotlib ``` 这一步骤提供了必要的基础环境支持[^1]。 --- #### 基本概念:Figure 和 Axes Matplotlib 的核心组件包括 `Figure` 和 `Axes`。 - **Figure** 表示整个画布或图像区域。 - **Axes** 则表示具体的坐标系(即图表所在的子区域)。 通过这些对象的操作,可以灵活控制图形的布局和样式[^2]。 --- #### 创建简单图表 以下是几个常见的图表类型及其绘制方法: ##### 折线图 折线图是最基本的数据展示形式之一。下面是一个简单的例子: ```python import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) # 在区间 [0, 10] 上生成均匀分布的 100 个点 y = np.sin(x) plt.plot(x, y, label='Sine Wave') # 添加标签以便后续标注 plt.title('Simple Sine Wave Plot') plt.xlabel('X-axis Label') plt.ylabel('Y-axis Label') plt.legend() plt.show() ``` 此代码展示了如何利用 `plot()` 函数绘制一条正弦曲线,并设置了标题、轴标签以及图例。 --- ##### 柱状图 柱状图适用于比较不同类别的数量关系。例如: ```python import matplotlib.pyplot as plt data = [5, 20, 15, 25, 10] plt.bar(range(len(data)), data, color=['red', 'blue', 'green', 'purple', 'orange']) plt.xticks(range(len(data)), ['A', 'B', 'C', 'D', 'E']) # 设置 X 轴刻度名称 plt.title('Bar Chart Example') plt.show() ``` 上述脚本定义了一组高度值并调用了 `bar()` 方法生成对应的条形图[^4]。 --- ##### 三维线框图 对于更复杂的空间数据分析场景,可借助 Matplotlib 实现三维可视化效果。如下所示为一个典型的三维线框图实现方式: ```python import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D x1 = np.arange(-5, 5, 0.25) y1 = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(x1, y1) Z = np.sin(np.sqrt(X**2 + Y**2)) fig = plt.figure() ax = fig.add_subplot(111, projection="3d") ax.plot_wireframe(X, Y, Z, rstride=3, cstride=2) plt.show() ``` 这段代码构建了一个基于网格数据集的三维表面模型,并应用了特定步长参数调整细节密度[^5]。 --- #### 图像保存功能 除了实时预览外,还可以将最终成果导出至文件系统中永久存储下来。比如采用 PNG 格式的输出操作如下: ```python plt.savefig('output_figure.png', dpi=300) ``` 这里指定了目标路径名以及分辨率选项以优化质量表现。 --- ### 总结 以上内容涵盖了从入门到高级的一些常用技巧介绍,帮助初学者快速上手掌握 Matplotlib 工具箱的核心能力。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值