如何将Matplotlib中pcolormesh生成的QuadMesh输出保存到文件?
需求与问题
我需要将Matplotlib中pcolormesh输出的QuadMesh对象保存到文件中。当前图形的坐标轴子元素列表如下:
[<matplotlib.lines.Line2D at 0x7fca1e4a7b20> <matplotlib.lines.Line2D at 0x7fca1e4a7d30> <matplotlib.lines.Line2D at 0x7fca1e4d0b20> <matplotlib.collections.QuadMesh at 0x7fca1e063f40> <matplotlib.spines.Spine at 0x7fca1e486890> <matplotlib.spines.Spine at 0x7fca1e4869b0> <matplotlib.spines.Spine at 0x7fca1e486ad0> <matplotlib.spines.Spine at 0x7fca1e486bf0> <matplotlib.axis.XAxis at 0x7fca1e486830> <matplotlib.axis.YAxis at 0x7fca1e4870d0> Text(0.5, 1.0, ''), Text(0.0, 1.0, ''), Text(1.0, 1.0, ''), <matplotlib.legend.Legend at 0x7fca1e487310> <matplotlib.patches.Rectangle at 0x7fca1e4a5840>]
我的目标是保存其中的<matplotlib.collections.QuadMesh at 0x7fca1e063f40>实例。
临时实现方案
我已经通过以下代码实现了功能,但该代码必须在图形渲染完成后执行才能生效:
quad_mesh = ax.get_children()[3] face_colors = quad_mesh.get_facecolors() # 90601 x 4 numpy array
这些quad_mesh._facecolors值共90601个(即301²),是按照quad_mesh._coordinates的顺序排列的,因此我将其重塑为正确形状后转换为图像保存:
import numpy as np from PIL import Image face_colors_reshaped = face_colors.reshape((301, 301, 4)) face_colors_reshaped_8 = (face_colors_reshaped * 255).astype(np.uint8) im = Image.fromarray(face_colors_reshaped_8).transpose(Image.FLIP_TOP_BOTTOM) im.save('quad_mesh.png')
想请教有没有更优的实现方法。
内容的提问来源于stack exchange,提问作者Atcold
相关产品推荐
相关产品推荐

