粘贴到 pdf 时如何解决扭曲的图像

问题描述 投票:0回答:0

我正在尝试使用

reportlab
中的
python
生成 pdf 报告,其中我首先创建了某些可视化效果 - 将它们保存为图像,现在我希望将它们粘贴到报告中。

然而,在这样做时图像似乎扭曲了宽高比。我不确定如何纠正这个问题,而是为什么会这样。

我正在使用

plt.savefig()
保存图像并使用
canvas.drawImage()
绘制图像。

示例屏幕截图显示它在 pdf 报告中的外观:

Report screenshot

源图像看起来不错,当我将它们作为 png 文件打开时,在粘贴时它会变形。

1st image

2nd image

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
import seaborn as sns
import matplotlib.pyplot as plt


font = "Times New Roman"
data = {'x': ['Categorical variable 1', 'Dummy text 3', 'Filers part 4', 'Ghost dataa 2'],
        'y': [10, 5, 8, 12],
        'a' : [-5,-8,-9,-10]}

total = max(data['y'])
c = canvas.Canvas("dummy.pdf", pagesize=letter)

fig, ax = plt.subplots(figsize=(20,15))
blue= (0.67,  0.75, 0.90)
light_orange = (1.0, 0.8, 0.64)
ax = sns.barplot(x=data['y'], y=data['x'] ,orient='h', color= light_orange, width=0.6)
ax.bar_label(ax.containers[0], fontsize=50)
plt.box(False)
ax.set_xlabel('', visible=False)
ax.tick_params(axis='y', which='major', labelsize=65)
ax.tick_params(axis='x', which='major', labelsize=50)
plt.yticks(fontname=font)
ax.set_ylabel('', visible=False)
#plt.rc('axes', labelsize=5)
plt.xticks(list(range(0,total,int(0.2*total))),[str(x)+'%' for x in list(range(0,110,20))])
plt.savefig(f'./Visualizations/dummy1.png', dpi=300, bbox_inches='tight')


fig, ax = plt.subplots(figsize=(70,15))
ax1 = sns.barplot(x='y', y='x', data=data,color=blue, lw =0, width=0.6)
sns.barplot(x='a', y='x', data=data,color=light_orange, lw =0, width=0.6)
ax.tick_params(axis='y', which='major', labelsize=65)
ax.tick_params(axis='x', which='major', labelsize=50)
plt.yticks(fontname=font)
plt.xticks(list(range(-30,30,6)), [str(i) + '%' for i in range(-30,30,6)])
ax.set_xlabel('', visible=False)
plt.box(False)
colors = {'Y': blue, 'A':  light_orange}
labels = list(colors.keys())
handles = [plt.Rectangle((0, 0), 1, 1, color=colors[label]) for label in labels]
plt.legend(handles, labels, fontsize=50)
# set the chart title
# show the chart
plt.savefig(f'./Visualizations/dummy2.png')

c.drawImage('./Visualizations/dummy1.png', 20, 625, 200,150)
c.drawImage('./Visualizations/dummy2.png', 20, 395, 450,220)
c.save()

编辑:上面是示例,这有点像最终报告的样子:

如您所见,有多个图像,目前有些图像的宽高比不对。

python matplotlib reportlab aspect-ratio
© www.soinside.com 2019 - 2024. All rights reserved.