Matplotlib入门篇,也可以很酷炫

今天写一篇 Matplotlib 的入门教程。

Matplotlib 是 Python 数据可视化库,广泛应用在数据分析和机器学习中。

1. 第一张图

Matplotlib 支持面向对象和pyplot接口两种方式画图。

以这两种方式为例,画出如下图所示的函数图。

y=x^2

面向对象方式

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2, 100)

fig, ax = plt.subplots()
ax.plot(x, x**2) # 折线图
ax.set_xlabel('x') # 设置横坐标名称
ax.set_ylabel('y') # 设置纵坐标标签
ax.set_title("y = x^2") # 设置标题

plt.show()

plt.subplots() 函数返回figax,分别是Figure对象和Axes对象。前者代表画布,后者代表画布上的绘图区域,很显然画布和绘图区域是一对多的关系。

之后关于绘图的设置,都通过Axes对象完成。

pyplot方式

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2, 100)

plt.figure()
plt.plot(x, x**2)
plt.xlabel('x')
plt.ylabel('y')

plt.show()

pyplot方式绘图和设置都通过plt来完成,没有对象的概念。

虽然这两种方式都能画图,但官方更建议采用面向对象的方式。

2. 支持多种图形

除了上面例子中看到的折线图,Matplotlib 还支持以下图形:

  • stackplot:堆叠图

  • bar/barh:柱状图

  • hist:直方图

  • pie:饼形图

  • scatter:散点图

  • contourf:等高线图

  • boxplot:箱型图

  • violinplot:提琴图

另外,Matplotlib 还是支持 3D 绘图

3. 常见设置

在第一小节的例子里,我们通过set_xlabelset_title设置坐标轴名称和标题。

除此之外,还可以添加注释和图例。

x = np.linspace(0, 2, 100)

fig, ax = plt.subplots()
ax.plot(x, x**2, label='二次函数')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title("y = x^2")

# 添加注释
ax.annotate('坐标(1,1)', xy=(1, 1), xytext=(0.5, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05))
# 添加图例
ax.legend()

还可以设置坐标轴的格式

ax.xaxis.set_major_formatter('x坐标{x}')

如果坐标轴是日期会非常有用,可以将日期转成周、月、季度等格式。

4. 一个画布多图形

前面提到过,一个画布可以有多个绘图区域。

下面使用plt.subplots()函数可以创建2行2列,4个绘图区域。

import matplotlib.pyplot as plt
import numpy as np

fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(5.5, 3.5),
                        constrained_layout=True)
# add an artist, in this case a nice label in the middle...
for row in range(2):
    for col in range(2):
        axs[row, col].annotate(f'axs[{row}, {col}]', (0.5, 0.5),
                               transform=axs[row, col].transAxes,
                               ha='center', va='center', fontsize=18,
                               color='darkgrey')
fig.suptitle('plt.subplots()')

也可以通过subplot_mosaic()函数创建

fig, axd = plt.subplot_mosaic([['upper left', 'upper right'],
                               ['lower left', 'lower right']],
                              figsize=(5.5, 3.5), constrained_layout=True)
for k in axd:
    annotate_axes(axd[k], f'axd["{k}"]', fontsize=14)
fig.suptitle('plt.subplot_mosaic()')

通过subplot_mosaic()函数,还可以将其他几个绘图区域合并成一个。

fig, axd = plt.subplot_mosaic([['upper left', 'right'],
                               ['lower left', 'right']],
                              figsize=(5.5, 3.5), constrained_layout=True)
for k in axd:
    annotate_axes(axd[k], f'axd["{k}"]', fontsize=14)
fig.suptitle('plt.subplot_mosaic()')

通过 GridSpec 也可以创建更复杂的绘图区域。

fig = plt.figure(constrained_layout=True)
gs0 = fig.add_gridspec(1, 2)

gs00 = gs0[0].subgridspec(2, 2)
gs01 = gs0[1].subgridspec(3, 1)

for a in range(2):
    for b in range(2):
        ax = fig.add_subplot(gs00[a, b])
        annotate_axes(ax, f'axLeft[{a}, {b}]', fontsize=10)
        if a == 1 and b == 1:
            ax.set_xlabel('xlabel')
for a in range(3):
    ax = fig.add_subplot(gs01[a])
    annotate_axes(ax, f'axRight[{a}, {b}]')
    if a == 2:
        ax.set_ylabel('ylabel')

fig.suptitle('nested gridspecs')

5. 高级用法

Matplotlib 很强大,设置很灵活,比如,折线图可以用极坐标画图

稍加改造还可以画出玫瑰图。

折线图隐藏坐标轴和边框,再结合注释就可以画出时间轴

多图组合形成更复杂的统计图

Matpolitlib还支持图形动画和交互式。

今天这篇文章只介绍了 Maptplotlib 很初级的一部分内容,它本身内容非常丰富、也很复杂。后面有机会我们可以介绍更深入的内容。

以上就是本次分享的所有内容,如果你觉得文章还不错,欢迎关注公众号:Python编程学习圈,每日干货分享,发送“J”还可领取大量学习资料,内容覆盖Python电子书、教程、数据库编程、Django,爬虫,云计算等等。或是前往编程学习网,了解更多编程技术知识。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值