Search code examples
pythonplotly

Adding two Figures to in one pdf file


How can I add two figures ( one bar chart and one table ) in one pdf file? What I am doing now is:

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")

Successfully creating 2 pdfs. Is there a way to achieve this ?


Solution

  • Use PdfPages to solve your problem. I wrote this small code for an example:

    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()
    

    Hope this helps.