且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

matplotlib显示的图形与从show()窗口保存的图形不同

更新时间:2023-11-23 23:40:04

当您以 png/jpg 格式保存图形时,您必须对其进行光栅化,将其转换为有限数量的像素.如果要保持完整的分辨率,则有几种选择:

When you save a figure in png/jpg you are forced to rasterize it, convert it to a finite number of pixels. If you want to keep the full resolution, you have a few options:

  • 使用非常高的 dpi 参数,例如900.保存绘图将很慢,许多图像查看器将需要一些时间来打开它,但是信息在那里,您可以随时对其进行裁剪
  • 保存图像数据,以及用于绘制曲线的确切数字.每当需要检查时,都可以以交互方式将其加载到Matplotlib中,导航到所需的角并保存.
  • 使用 SVG:它是一种矢量图形格式,因此您不仅限于像素.
  • Use a very high dpi parameter, like 900. Saving the plot will be slow, and many image viewers will take some time to open it, but the information is there and you can always crop it.
  • Save the image data, the exact numbers you used to make the plot. Whenever you need to inspect it, load it in Matplotlib in interactive mode, navigate to your desired corner, and save it.
  • Use SVG: it is a vector graphics format, so you are not limited to pixels.

以下是使用 SVG 的方法:

Here is how to use SVG:

import matplotlib
matplotlib.use('SVG')
import matplotlib.pyplot as plt

# Generate the image
plt.imshow(image, interpolation='none')
plt.savefig('output_image')

要保存真实的SVG,您需要从一开始就使用SVG后端,不幸的是,该后端与交互模式不兼容.某些后端(例如GTKCairo)似乎允许两者同时使用,但结果仍然栅格化,而不是真正的SVG.

To save a true SVG you need to use the SVG backend from the beginning, which is unfortunately, incompatible with interactive mode. Some backends, like GTKCairo seem to allow both, but the result is still rasterized, not a true SVG.

至少在我所知的范围内,这可能是matplotlib中的错误,没有记录.

This may be a bug in matplotlib, at least, to the best of my knowledge, it is not documented.