优秀的编程知识分享平台

网站首页 > 技术文章 正文

matplotlib用面向对象的API绘图(五)

nanyue 2024-10-14 11:32:31 技术文章 8 ℃

导读

对于需要高级功能的复杂应用程序,例如贴片、元素容器、使用事件的交互式绘图、回调、动画和小部件,我们必须使用面向对象的API。 然而,它需要有相当多的Python编码经验来充分利用这个API。 随着Matplotlib新版本的发布,越来越多的这些功能正在迁移到pyplot API中,减少了对面向对象的API的依赖。

代码环境约定

matplot系列文章默认运行在jupyterlab中,所有代码cell都在以下代码环境后运行

import matplotlib as mpl
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd

# 全局配置
mpl.rcdefaults()
mpl.rcParams['font.family'] = "Microsoft YaHei"
mpl.rcParams["axes.unicode_minus"] = True # 正常显示负号
plt.style.use('ggplot')

pyplot API和面向对象API

本节中,我们将学习pyplot和面向对象API之间的区别。我们将绘制相同的相关矩阵,首先使用pyplot API,然后使用面向对象的API。

# pyplot API
wine_quality = pd.read_csv('../winequality.csv', delimiter=';')
corr = wine_quality.corr()

plt.figure(figsize=(10, 8))
plt.imshow(corr, cmap='hot')
plt.colorbar();
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from IPython.display import display
fig = Figure(figsize=(10, 8))

# 将figure关联到画布上
FigureCanvas(fig)
axs = fig.add_subplot(111)
corimage = axs.imshow(corr, cmap='hot')
fig.colorbar(corimage)
display(fig)

绘制贴片

Matplotlib提供了一些特殊类型的图形,使用补丁和容器类。在本节中,我们将学习如何使用面向对象的API来使用贴片。 在下一节中,我们将学习容器类。

from matplotlib.backends import backend_agg
from matplotlib.patches import Ellipse, Polygon

figure_manager = backend_agg.new_figure_manager(1, figsize=(10, 6))
fig = figure_manager.canvas.figure

axs1 = fig.add_subplot(121)
axs1.add_patch(Ellipse((3, 1.0), 4, 1.0, hatch='/', facecolor='g'))
axs1.set_xlim((0, 6))
axs1.set_ylim((0, 2.5))

axs2 = fig.add_subplot(122)
axs2.add_patch(Polygon([[0, 0], [4, 1.1], [6, 2.5], [2, 1.4]],
lw=5, facecolor='k', edgecolor='skyblue', hatch='+*'))
axs2.set_xlim((0, 6))
axs2.set_ylim((0, 2.5))
display(fig)

容器

Collections是共享许多属性的类似对象的容器。

from matplotlib import collections
from matplotlib.backends import backend_agg

nsizes = 50 
npts = 100 
r = np.arange(nsizes)
theta = np.linspace(0, 2*np.pi, nsizes)
xx = r * np.sin(theta)
rs = np.random.RandomState([125])
xo = rs.randn(npts)
yo = rs.randn(npts)
xyo = list(zip(xo, yo))

figure_manager = backend_agg.new_figure_manager(1, figsize=(10, 6))
fig = figure_manager.canvas.figure
axs1 = fig.add_subplot(111)
# 6边形集合
col = collections.RegularPolyCollection(6,
						sizes=np.fabs(xx) * 20, offsets=xyo,
						transOffset=axs1.transData)
axs1.add_collection(col, autolim=True)
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w', 'tab:blue', 'tab:orange', 'tab:green', 'tab:red',
'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan']
col.set_color(colors)
axs1.autoscale_view()
display(fig)

本文章参考《Matplotlib 3.0 Cookbook》,作者:Srinivasa Rao Poladi

欢迎各位看官关注转发收藏评论,thanks by 渝玖玖

Tags:

最近发表
标签列表