[英]Adding two Figures to in one pdf file
如何在一個pdf
文件中添加兩個數字(一個bar chart
和一個table
)? 我現在正在做的是:
from plotly import graph_objs as go
import numpy as np
import os
from IPython.display import Image
# Chart product views
fig = go.Figure(
data = [go.Bar(
x=[
"01/09/2019 - 07/09/2019",
"08/09/2019 - 14/09/2019",
"15/09/2019 - 21/09/2019",
"22/09/2019 - 28/09/2019"
],
y=[15, 25, 35, 32]
),
],
layout=dict(
yaxis=dict(
title="Product views"
),
autosize=False,
width=1000,
height=600,
),
)
# Table product views
fig2 = go.Figure(
data=[
go.Table(
header=dict(values=["Period", "Views"]),
cells=dict(values=[
[
"01/09/2019 - 07/09/2019",
"08/09/2019 - 14/09/2019",
"15/09/2019 - 21/09/2019",
"22/09/2019 - 28/09/2019"
],
[15, 25, 35, 32]
])
)
],
layout=dict(
autosize=False,
width=800,
height=300,
title=dict(
text="<b>Library Shelving</b> statistic"
)
)
)
if not os.path.exists("images"):
os.mkdir("images")
fig.write_image("images/fig1.pdf")
fig2.write_image("images/fig2.pdf")
成功創建 2 個 pdf。 有沒有辦法做到這一點?
使用PdfPages
解決您的問題。 我寫了這個小代碼作為一個例子:
import matplotlib.backends.backend_pdf
import matplotlib.pyplot as plt
import numpy as np
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot([1, 2, 3], [1, 2, 3])
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
x = np.linspace(1, 20)
ax2.plot(x, x * x)
for fig in [fig1, fig2]:
pdf.savefig(fig)
pdf.close()
希望這可以幫助。
我已經能夠使用以下方法完成此操作:
plotly.io.to_image()
將數字寫入圖像字節數據PIL.Image.open()
讀取字節數據PIL.Image.convert()
將字節數據轉換為 RGBio.BytesIO()
臨時存儲轉換后的圖像數據PIL.Image.save()
將第一個圖像保存到 PDF 和 append 圖中的所有其他 PDF 到第一個圖像結果將是圖像的多頁 PDF。
您可能需要pip install pillow
import plotly.io as pio
import io
from PIL import Image
figures = [fig1, fig2, fig3]
image_list = [pio.to_image(fig, format='png', width=1440, height=900, scale=1.5) for fig in figures]
for index, image in enumerate(image_list):
with io.BytesIO() as tmp:
tmp.write(image) # write the image bytes to the io.BytesIO() temporary object
image = Image.open(tmp).convert('RGB') # convert and overwrite 'image' to prevent creating a new variable
image_list[index] = image # overwrite byte image data in list, replace with PIL converted image data
# pop first item from image_list, use that to access .save(). Then refer back to image_list to append the rest
image_list.pop(0).save(r'/Users/USERNAME/plotly_dash.pdf', 'PDF',
save_all=True, append_images=image_list, resolution=100.0) # TODO improve resolution
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.