Python matplotlib另存为TIFF

时间:2016-06-21 13:13:57

标签: python matplotlib tiff

有谁知道如何将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')

4 个答案:

答案 0 :(得分: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()

答案 1 :(得分:7)

太好了!谢谢Martin Evans。 但是,对于那些希望在Python3.x中实现这一目标的人来说,小修补程序(因为cStringIO模块不可用;我宁愿使用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()

答案 2 :(得分:1)

Matplotlib does support tif since version 1.1,但该支持是可选的,并不明显。只要安装了pillow,就可以保存为tif,就像可以保存为任何其他格式一样。因此,您的示例将仅仅是:

option

答案 3 :(得分:1)

您要做的就是安装枕头。 然后,您可以使用以下方式:

public function products()
{
    return $this->hasMany(Product::class, 'category_id');
}