将Matplotlib图保存为TIFF

问题描述 投票:11回答:2

有谁知道如何将Matplotlib图保存为* .tiff?似乎Python不支持这种格式,而期刊经常要求这种格式。

我正在添加一些最小的代码:

# -*- coding: utf-8 -*-

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

# fig setup
fig = plt.figure(figsize=(5,5), dpi=300)
ax = fig.gca(projection='3d')
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
ax.set_zlim([-1,1])
ax.axes.xaxis.set_ticklabels([])
ax.axes.yaxis.set_ticklabels([])
ax.axes.zaxis.set_ticklabels([])

# draw a surface
xx, yy = np.meshgrid(range(-1,2), range(-1,2))
zz = np.zeros(shape=(3,3))
ax.plot_surface(xx, yy, zz, color='#c8c8c8', alpha=0.3)
ax.plot_surface(xx, zz, yy, color='#b6b6ff', alpha=0.2)

# draw a point
ax.scatter([0],[0],[0], color='b', s=200)

这有效:

fig.savefig('3dPlot.pdf')

但这不是:

fig.savefig('3dPlot.tif')
python matplotlib tiff
2个回答
13
投票

作为一种解决方法,没有什么可以阻止您使用Python PIL包以TIFF格式保存图像:

# -*- coding: utf-8 -*-

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

from PIL import Image
import io

# fig setup
fig = plt.figure(figsize=(5,5), dpi=300)
ax = fig.gca(projection='3d')
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
ax.set_zlim([-1,1])
ax.axes.xaxis.set_ticklabels([])
ax.axes.yaxis.set_ticklabels([])
ax.axes.zaxis.set_ticklabels([])

# draw a surface
xx, yy = np.meshgrid(range(-1,2), range(-1,2))
zz = np.zeros(shape=(3,3))
ax.plot_surface(xx, yy, zz, color='#c8c8c8', alpha=0.3)
ax.plot_surface(xx, zz, yy, color='#b6b6ff', alpha=0.2)

# draw a point
ax.scatter([0],[0],[0], color='b', s=200)

#fig.savefig('3dPlot.pdf')

# Save the image in memory in PNG format
png1 = io.BytesIO()
fig.savefig(png1, format="png")

# Load this image into PIL
png2 = Image.open(png1)

# Save as TIFF
png2.save("3dPlot.tiff")
png1.close()

如果正在使用Python 2.x,请使用cStringIO而不是BytesIO,如下所示:

import cStringIO

# Replace the BytesIO() call with
png1 = cStringIO.StringIO()

7
投票

这很棒!感谢qazxsw poi。但是,对于那些想在qazxsw poi中实现它的人来说,小修正(因为Martin Evans模块不可用;我宁愿使用Python3.x

cStringIO

2
投票

BytesIO,但支持是可选的,并不明显。只要你安装了# -*- coding: utf-8 -*- from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np from PIL import Image from io import BytesIO # fig setup fig = plt.figure(figsize=(5,5), dpi=300) ax = fig.gca(projection='3d') ax.set_xlim([-1,1]) ax.set_ylim([-1,1]) ax.set_zlim([-1,1]) ax.axes.xaxis.set_ticklabels([]) ax.axes.yaxis.set_ticklabels([]) ax.axes.zaxis.set_ticklabels([]) # draw a point ax.scatter([0],[0],[0], color='b', s=200) # save figure # (1) save the image in memory in PNG format png1 = BytesIO() fig.savefig(png1, format='png') # (2) load this image into PIL png2 = Image.open(png1) # (3) save as TIFF png2.save('3dPlot.tiff') png1.close() ,就可以保存为tif,就像你可以保存到任何其他格式一样。因此,您的示例只是:

Matplotlib does support tif since version 1.1
© www.soinside.com 2019 - 2024. All rights reserved.