作为一个R语言已经练习了两年半的生信小弟,毅然决然的投入Python的怀抱。仅以此文记录Python学习的一些笔记。
01 初识 matplotlib
Matplotlib 可视化需要先生成一个Figure对象,代表整个图形窗口。Figure 对象可以包含一个或者多个Axes 子图。而Axes 子图呢,就是我们后续画图的位置。
创建好Axes 子图 后,就可以使用 Axes.plot函数在 Axes 子图上可视化我们的数据 。
我是这么简单理解的,假如我们要用 Matplotlib 进行可视化,我们第一步要创建一个 Figure对象,相当于开辟了一个大大的画布。然后,你可以决定,在这个大画布上要画一个还是几个图案。一个图案就是一个 Axes 。接下来我们就可以操作 Axes 进行每个图案的绘制。
matplotlib Figure 的组成:
接下来,还是通过具体例子来说明下:
1、 创建一个带有 Axes 的 Figure
# 导入 matplotlib.pyplot 模块并命名为 pltimport matplotlib.pyplot as plt
# 创建一个新的 Figure 对象,fig 代表整个图形窗口fig = plt.figure()
# 在 Figure 对象中创建一个子图(Axes),ax 代表绘图区域ax = fig.subplots()
# 在坐标轴 ax 上绘制一条线,x 轴数据为 [1, 2, 3, 4],y 轴数据为 [0, 0.5, 1, 0.2]# ax.plot() 是绘制折线图的主要方法ax.plot([1, 2, 3, 4], [0, 0.5, 1, 0.2])
# 调用 plt.show() 显示图形窗口# 这一步是必须的,因为它会把图形呈现出来plt.show()
fig 是整个图形的容器,负责管理所有的图形元素。
ax 是具体的坐标轴对象,负责实际绘制数据。
2、 使用 plt.subplots() 同时创建 fig 和 ax对象
(这个是最常用的方式!可以每次都用这个方式开头)
plt.subplots() 是 matplotlib 中一个非常常用的函数,它可以用来同时创建一个 Figure 对象和一个或多个 Axes 对象。它简化了 Figure 和 Axes 的创建过程,适合用于快速绘图。
import matplotlib.pyplot as plt
# 创建一个 Figure 对象和一个 Axes 对象fig, ax = plt.subplots()
# 绘制数据ax.plot([1, 2, 3, 4], [0, 0.5, 1, 0.2])
# 显示图形plt.show()
3、 创建一个 22 子图布局的 Figure
# 创建一个 Figure 对象fig, axs = plt.subplots(2, 2, figsize=(8, 6)) #
# 绘制数据到不同的 Axes 上axs[0, 0].plot([1, 2, 3], [1, 4, 9])axs[0, 0].set_title('Plot 1')
axs[0, 1].plot([1, 2, 3], [2, 3, 4])axs[0, 1].set_title('Plot 2')
axs[1, 0].plot([1, 2, 3], [3, 2, 1])axs[1, 0].set_title('Plot 3')
axs[1, 1].plot([1, 2, 3], [4, 5, 6])axs[1, 1].set_title('Plot 4')
# 自动调整子图间距plt.tight_layout()
# 显示图形plt.show()
OK,matplotlib 最使用基础的知识我们已经get了,后面再使用时都是以此为基础的:创建Figure 创建 ax 在ax上画我们的数据 ···
02 柱状图
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fruits = ['apple', 'blueberry', 'cherry', 'orange']counts = [40, 100, 30, 55]bar_labels = ['red', 'blue', '_red', 'orange']bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']
ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
ax.set_ylabel('fruit supply')ax.set_title('Fruit supply by kind and color')ax.legend(title='Fruit color')
plt.show()
02 分组柱状图
领取专属 10元无门槛券
私享最新 技术干货