Python: 如何将statsmodels结果保存为图片文件?

Python: How to save statsmodels results as image file?

我正在使用 statsmodels 进行 OLS 估计。可以使用 print(results.summary()) 在控制台中研究结果。我想将完全相同的 table 存储为 .png 文件。下面是一个带有可重现示例的片段。

import pandas as pd
import numpy as np
import matplotlib.dates as mdates
import statsmodels.api as sm

# Dataframe with some random numbers
np.random.seed(123)
rows = 10
df = pd.DataFrame(np.random.randint(90,110,size=(rows, 2)), columns=list('AB'))
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist()
df['dates'] = datelist 
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
print(df)

# OLS estimates using statsmodels.api
x = df['A']
y = df['B']

model = sm.OLS(y,sm.add_constant(x)).fit()

# Output
print(model.summary())

我根据建议 here 进行了一些幼稚的尝试,但我怀疑我偏离了目标:

os.chdir('C:/images')
sys.stdout = open("model.png","w")
print(model.summary())
sys.stdout.close()

到目前为止,这只会引发一条很长的错误消息。

感谢您的任何建议!

这是一项非常不寻常的任务,您的方法有点疯狂。您正在尝试将一个字符串(在某些度量 space 中没有位置)与一些图像(基于绝对位置;至少对于基于像素的格式 -> png、jpeg 和 co.)组合。

无论做什么,都需要一些文本渲染引擎!

我尝试使用 pillow,但结果很糟糕。可能是因为它非常有限,而且 post 处理抗锯齿并没有节省任何东西。但也许我做错了什么。

from PIL import Image, ImageDraw, ImageFont
image = Image.new('RGB', (800, 400))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("arial.ttf", 16)
draw.text((0, 0), str(model.summary()), font=font)
image = image.convert('1') # bw
image = image.resize((600, 300), Image.ANTIALIAS)
image.save('output.png')

当您使用 statsmodels 时,我假设您已经掌握了 matplotlib。这个也可以用。这是一些方法,虽然不完美,但还不错(一些换行;我不知道为什么;编辑: OP 设法通过使用 monospace-字体):

import matplotlib.pyplot as plt
plt.rc('figure', figsize=(12, 7))
#plt.text(0.01, 0.05, str(model.summary()), {'fontsize': 12}) old approach
plt.text(0.01, 0.05, str(model.summary()), {'fontsize': 10}, fontproperties = 'monospace') # approach improved by OP -> monospace!
plt.axis('off')
plt.tight_layout()
plt.savefig('output.png')

输出:

编辑: OP 设法通过使用单space-字体改进了 matplotlib 方法!我把它合并在这里,它反映在输出图像中。

将此作为演示并研究 python 的文本呈现选项。也许 matplotlib-approach 可以改进,但也许你需要使用像 pycairo. Some SO-discussion.

这样的东西

备注:在我的系统上,您的代码确实给出了这些警告!

编辑: you can ask statsmodels for a latex-representation. So i recommend using this, probably writing this to a file and use subprocess to call pdflatex or something similar (here some similar approach)。 matplotlib 也可以使用乳胶(但我不会测试它,因为我目前在 windows 上)但在这种情况下,我们再次需要以某种方式将文本调整为 window 比率(与完整的乳胶文档相比例如给定一些 A5 格式)。