Python Matplotlib - 如何绘制高分辨率图形?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39870642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:50:41  来源:igfitidea点击:

Matplotlib - How to plot a high resolution graph?

pythonmatplotlib

提问by esilik

I've used matplotlib for plotting some experimental results (discussed it in here: Looping over files and plotting. However, saving the picture by clicking right to the image gives very bad quality / low resolution images.

我已经使用 matplotlib 绘制了一些实验结果(在这里讨论:循环文件和绘图。但是,通过单击图像的右侧来保存图片会产生非常差的质量/低分辨率图像。

from glob import glob
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

# loop over all files in the current directory ending with .txt
for fname in glob("./*.txt"):
    # read file, skip header (1 line) and unpack into 3 variables
    WL, ABS, T = np.genfromtxt(fname, skip_header=1, unpack=True)

    # first plot
    plt.plot(WL, T, label='BN', color='blue')

    plt.xlabel('Wavelength (nm)')
    plt.xlim(200,1000)
    plt.ylim(0,100)
    plt.ylabel('Transmittance, %')
    mpl.rcParams.update({'font.size': 14})
    #plt.legend(loc='lower center')
    plt.title('')
    plt.show()
    plt.clf()


    # second plot
    plt.plot(WL, ABS, label='BN', color='red')
    plt.xlabel('Wavelength (nm)')
    plt.xlim(200,1000)
    plt.ylabel('Absorbance, A')
    mpl.rcParams.update({'font.size': 14})
    #plt.legend()
    plt.title('')
    plt.show()
    plt.clf()

Example graph of what I'm looking for: example graph

我正在寻找的示例图示例图

回答by Ohad Eytan

You can use savefig()to export to an image file:

您可以使用savefig()导出到图像文件:

plt.savefig('filename.png')

In addition, you can specify the dpiargument to some scalar value, for example:

此外,您可以将dpi参数指定为某个标量值,例如:

plt.savefig('filename.png', dpi=300)

回答by Ophir Carmi

use plt.figure(dpi=1200)before all your plt.plot...and at the end use plt.savefig(...see: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figureand http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig

使用plt.figure(dpi=1200)之前plt.plot...和最后使用plt.savefig(...请参阅:http: //matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figurehttp://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig

回答by JMat

You can save your graph as svg for a lossless quality:

您可以将图形保存为 svg 以获得无损质量:

import matplotlib.pylab as plt

x = range(10)

plt.figure()
plt.plot(x,x)
plt.savefig("graph.svg")

回答by Christian Seitz

For future readers who found this question while trying to save high resolution images from matplotlib as I am, I have tried some of the answers above and elsewhere, and summed them up here.

对于在尝试从 matplotlib 保存高分辨率图像时发现这个问题的未来读者,我已经尝试了上面和其他地方的一些答案,并在此处进行了总结。

Best result: plt.savefig('filename.pdf')

最佳结果plt.savefig('filename.pdf')

and then converting this pdf to a png on the command line so you can use it in powerpoint:

然后在命令行上将此pdf转换为png,以便您可以在powerpoint中使用它:

pdftoppm -png -r 300 filename.pdf filename

pdftoppm -png -r 300 filename.pdf filename

Less successful test #1: plt.savefig('filename.png', dpi=300)

不太成功的测试#1plt.savefig('filename.png', dpi=300)

This does save the image at a bit higher than the normal resolution, but it isn't high enough for publication or some presentations. Using a dpi value of up to 2000 still produced blurry images when viewed close up.

这确实以比正常分辨率高一点的方式保存图像,但对于出版物或某些演示来说还不够高。使用高达 2000 的 dpi 值在近距离观看时仍会产生模糊的图像。

Less successful test #2: plt.savefig('filename.pdf')

不太成功的测试#2plt.savefig('filename.pdf')

This cannot be opened in Microsoft Office Professional Plus 2016 (so no powerpoint), same with Google Slides.

这不能在 Microsoft Office Professional Plus 2016 中打开(所以没有powerpoint),与谷歌幻灯片相同。

Less successful test #3: plt.savefig('filename.svg')

不太成功的测试#3plt.savefig('filename.svg')

This also cannot be opened in powerpoint or Google Slides, with the same issue as above.

这也无法在 powerpoint 或 Google Slides 中打开,与上述问题相同。

Less successful test #4: plt.savefig('filename.pdf')

不太成功的测试#4plt.savefig('filename.pdf')

and then converting to png on the command line:

然后在命令行上转换为 png:

convert -density 300 filename.pdf filename.png

convert -density 300 filename.pdf filename.png

but this is still too blurry when viewed close up.

但是当近距离观看时,这仍然太模糊了。

Less successful test #5: plt.savefig('filename.pdf')

不太成功的测试#5plt.savefig('filename.pdf')

and opening in GIMP, and exporting as a high quality png (increased the file size from ~100 KB to ~75 MB)

并在 GIMP 中打开,并导出为高质量的 png(将文件大小从 ~100 KB 增加到 ~75 MB)

Less successful test #6: plt.savefig('filename.pdf')

不太成功的测试 #6plt.savefig('filename.pdf')

and then converting to jpeg on the command line:

然后在命令行上转换为 jpeg:

pdfimages -j filename.pdf filename

pdfimages -j filename.pdf filename

This did not produce any errors but did not produce an output on Ubuntu even after changing around several parameters.

这没有产生任何错误,但即使在更改了几个参数后也没有在 Ubuntu 上产生输出。

回答by Jason

For saving the graph:

保存图形:

matplotlib.rcParams['savefig.dpi'] = 300

matplotlib.rcParams['savefig.dpi'] = 300

For displaying the graph when you use plt.show():

用于在使用时显示图形plt.show()

matplotlib.rcParams["figure.dpi"] = 100

matplotlib.rcParams["figure.dpi"] = 100

Just add them at the top

只需将它们添加到顶部

回答by Jalo

At the end of your for()loop, you can use the savefig()function instead of plt.show()and set the name, dpi and format of your figure.

for()循环结束时,您可以使用该savefig()函数代替plt.show()并设置图形的名称、dpi 和格式。

E.g. 1000 dpi and eps format are quite a good quality, and if you want to save every picture at folder ./with names 'Sample1.eps', 'Sample2.eps', etc. you can just add the following code:

例如,1000 dpi 和 eps 格式的质量非常好,如果您想将每张图片保存在文件夹./ 中,名称为“Sample1.eps”、“Sample2.eps”等,您只需添加以下代码:

for fname in glob("./*.txt"):
    # Your previous code goes here
    [...]

    plt.savefig("./{}.eps".format(fname), bbox_inches='tight', format='eps', dpi=1000)