将matplotlib保存为最终给定大小(包括标题)

2024-05-19 01:43:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为出版制作数字。我需要最终的数字,包括标题和文本是3英寸宽,并作为.tiff文件保存。我知道我可以通过matplotlib使用 matplotlib.pyplot.figure图(图尺寸=(3,2),dpi=300) 但是,这只指定实际情节的大小,不包括标题和所有内容。此外,当我尝试此方法时,标题会从保存的.tiff文件中删除。当然,简单的解决办法是缩小绘图的大小,并手动将图形设置为正确的大小,但是有没有人知道一种自动方法,可以使绘图成为一个给定的最终大小,包括所有的钟声和口哨声?你知道吗

这是保存的输出图像(这是一个png,可以上传到stackoverflow)。注意,由于某种原因,情节标题被删掉了。enter image description here

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO


bent=[2.83263904,2.75860489,2.64546045,2.4949913,2.34923737,2.16430217,2.02562783,1.82478841,1.70324689,1.70315642,1.39739535,1.33945747,1.22295623,1.15726486,1.08449954,0.96155077,0.90325786,0.84547091]
bent=[i/27 for i in bent]
print(bent)

planar=[4.11233905,3.93027011,3.65135645,3.38525615,3.1130921,2.81042899,2.58995789,2.36159934,2.15981447,1.9964454,1.74375941,1.63263452,1.48503205,1.38596544,1.26501988,1.17391638,1.07490417,0.99369748]
planar=[i/27 for i in planar]

bi=[2.51027966,2.56495852,2.47033072,2.33008642,2.19395126,2.13732249,1.80922673,1.76037446,1.52930137,1.56732451,1.33905847,1.24952153,1.15699233,1.08251496,0.98449116,0.93838164,0.86542147,0.725736]
bi=[i/34 for i in bi]

T=[3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

arr=[bi,bent,planar]
arr=np.array(arr)
arr=arr.T

font = {'family' : 'normal',
        'weight' : 'normal',
        'size'   : 8}

matplotlib.rc('font', **font)


fig = plt.figure(figsize=(3,2), dpi=300)

plt.title("-ΔS$_m$ vs T") #for Fe$_4$Gd
plt.xlabel('Temperature (K)')
plt.ylabel("$-ΔS_m$ ($J.K^{-1}.mol^{-1}n (e^{-})^{-1}$)")
MMM=('Fe$_4$Gd$_2$','Fe$_4$Gd bent','Fe$_4$Gd planar')

plt.plot(T,arr,'o')
plt.legend(MMM, loc='best')






# 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('TESTTESTTEST.tiff')
png1.close()

Tags: inimport标题formatplotlibsavepltarr

热门问题