bokeh save hvplot to pdf python

Bokeh provides an interactive rendering engine, while hvplot offers a high‑level API that maps Pandas data to Bokeh glyphs․ Together they enable quick visual exploration and seamless PDF export via hv․save, bridging data science and presentation workflows․ They embed in notebooks and export to PDF

Overview of Bokeh rendering engine

Bokeh’s rendering engine blends JavaScript and Python, converting Python objects into interactive visualizations for modern browsers․ A Python script creates a Bokeh model (e․g․, Figure, ColumnDataSource, or GlyphRenderer), which is serialised into a JSON document describing the scene graph, data, and layout․ The Document object manages callbacks, state, and server communication․

For static export, Bokeh provides export_png and export_svgs to capture canvas or SVG output․ These rely on headless browsers (e․g․, Selenium or PhantomJS) or cairosvg to rasterise the plot․ Combined with hvplot’s hv․save, the engine renders to SVG and converts to PDF via cairosvg or reportlab, preserving vector quality and interactivity․ The resulting PDF retains all vector elements, making it ideal for publication-quality figures and․

Role of hvplot in high-level plotting

hvplot is a high‑level plotting API that bridges Pandas, Dask, and GeoPandas with Bokeh, Matplotlib, and Plotly․ By calling df․hvplot, the library automatically infers the appropriate glyphs, scales, and layout, allowing users to generate complex visualizations with a single line of code․ It supports interactive features such as hover tooltips, linked brushing, and dynamic range selection out of the box․ hvplot’s design is modular: the core library delegates rendering to a chosen backend, while the hv․extension call configures the visual style and theme․ This separation of concerns means that the same hvplot call can produce a Bokeh figure for a notebook, a Plotly chart for a web dashboard, or a Matplotlib image for a static report․ Additionally, hvplot exposes a save function that serialises the figure to SVG, PNG, or PDF, leveraging the underlying backend’s export capabilities․ For PDF export, hvplot typically renders the plot to SVG and then uses cairosvg or reportlab to convert the vector graphics into a PDF file, preserving resolution and interactivity․ This workflow is particularly useful for researchers and data scientists who need reproducible, publication‑ready figures without writing boilerplate code․ By abstracting away the intricacies of each rendering engine, hvplot empowers users to focus on data exploration and storytelling rather than on the mechanics of plot generation․ Additional context․ More․!

Prerequisites for PDF Export

Before exporting hvplot figures to PDF, ensure that Bokeh, hvplot, and HoloViews are installed with comp versions․ Install cairosvg for SVG to PDF conversion and reportlab for PDF gen․ Verify that hv․extension('bokeh') is loaded and that your notebook․!

Required Python packages and versions

To reliably export hvplot figures to PDF, the environment must contain a consistent set of libraries․ The core stack is:

  • Python 3․8 or newer – older releases lack the typing hints used by hvplot․
  • Bokeh 3․3․x – the rendering engine that hvplot delegates to; 3․3;x supports the export_png hook used by hv․save․
  • HoloViews 1․17․x – the high‑level API that translates DataFrames into Bokeh glyphs․
  • hvplot 0․9․x – the convenience wrapper that exposes hv․save for PDF output․
  • cairosvg 2․5․x – converts the intermediate SVG to PDF․
  • reportlab 3․6․x – optional, used when cairosvg is unavailable․

Installation can be performed with pip install python==3․10 bokeh==3․3․0 holoviews==1․17․0 hvplot==0․9․0 cairosvg==2․5․2 reportlab==3․6․12․ Verify versions with pip list | grep -E 'bokeh|holoviews|hvplot|cairosvg|reportlab'․ Compatibility gaps between Bokeh 3․3 and hvplot 0․9 are known to cause rendering errors; avoid mixing 3․2․x with 0․9․x; Keep the JupyterLab extension hvplot-jupyter at 0․9․x to ensure in‑notebook previews match the exported PDF․ Finally, set hv․extension('bokeh', logo=False) before creating plots to suppress the default logo, which can interfere with PDF layout on some systems․

Installation can be performed with pip install python==3․10 bokeh==3․3․0 holoviews==1․17․0 hvplot==0․9․0 cairosvg==2․5․2 reportlab==3․6;12․ Verify versions with pip list | grep -E 'bokeh|holoviews|hvplot|cairosvg|reportlab'․ Compatibility gaps between Bokeh 3․3 and hvplot 0․9 are known to cause rendering errors; avoid mixing 3․2․x with 0․9․x․ Keep the JupyterLab extension hvplot-jupyter at 0․9․x to ensure in‑notebook previews match the exported PDF․ Finally, set hv․extension('bokeh', logo=False) before creating plots to suppress the default logo, which can interfere with PDF layout on some systems․

Running hv․save will generate a PDF that preserves vector graphics, ensuring crisp fonts and scalable charts․ For large datasets, consider using panel․io․export_pdf to stream directly to disk․

Set hv․save(․․․, backend='pdf') to bypass SVG and reduce size․

Ensuring Bokeh and hvplot compatibility

Compatibility hinges on matching major releases: Bokeh 3․3․x pairs best with hvplot 0․9․x, while Bokeh 3․2․x works with hvplot 0․8․x․ Begin by running import bokeh, hvplot, holoviews; print(bokeh․__version__, hvplot․__version__, holoviews․__version__) to confirm alignment․ If versions diverge, uninstall both packages and reinstall the matched pair via pip install bokeh==3․3․0 hvplot==0․9․0 holoviews==1․17․0․ Next, activate the Bokeh renderer explicitly: hv․extension('bokeh', logo=False)․ This forces hvplot to use Bokeh’s glyphs rather than the default Matplotlib backend, eliminating silent fallbacks that break PDF output․ For interactive notebooks, set panel․extension('bokeh') to keep the same rendering context․ When exporting, use hv․save(fig, 'plot․pdf', backend='pdf') – the backend='pdf' flag instructs hvplot to route through Bokeh’s export_png and cairosvg to produce vector PDF․ Verify that the Bokeh document is fully loaded before calling hv․save; otherwise, the PDF may contain incomplete glyphs․ A quick sanity check is to render the same figure with fig․show and compare the SVG output using fig․opts(tools=[])․save('temp․svg')․ If the SVG matches the PDF, the compatibility is solid․ Finally, keep the panel․io․export_pdf helper in mind for large datasets, as it streams directly to disk without intermediate PNG, reducing memory overhead and ensuring consistent vector quality across Bokeh and hvplot versions․ Use a dedicated virtual environment for each project to avoid cross‑dependency conflicts, and lock versions with pip freeze > requirements․txt before deployment․

Creating a Sample hvplot Figure

Generate a DataFrame, call df․hvplot․line, customize title, axis, and color, then display․ This quick example demonstrates hvplot’s concise syntax and prepares the figure for subsequent PDF export․ Use hv․save(fig,’plot․pdf’,backend=’pdf’)․

Generating a Bokeh plot via hvplot

To generate a Bokeh plot with hvplot, first import the required libraries:

import pandas as pd
import hvplot․pandas
hvplot․bokeh․extension

Create a simple time‑series DataFrame:

df = pd․DataFrame({
 'time': pd․date_range('2024-01-01', periods=100, freq='D'),
 'value': np․random․randn(100)․cumsum
})

Now produce a line plot:

plot = df․hvplot․line(
 x='time',
 y='value',
 title='Cumulative Sum',
 xlabel='Date',
 ylabel='Value',
 color='steelblue',
 line_width=2
)

The plot object is a HoloViews element that Bokeh renders․ You can further tweak it with ․opts:

plot = plot․opts(
 width=800,
 height=400,
 tools=['hover'],
 legend_position='top_left'
)

Finally, export the figure to PDF:

import hvplot as hv
hv․save(plot, 'plot․pdf', backend='pdf')

This sequence produces a static PDF that preserves the title, labels, and styling defined above․ The PDF export relies on Bokeh’s rendering engine, so ensure you have the latest bokeh and hvplot packages installed․

When exporting, Bokeh’s PDF backend requires a working font configuration․ If fonts are missing, the PDF may contain blank glyphs․ Installing the fonts-roboto package or setting hv․save(․․․, font='DejaVu Sans') ensures legible text․ Additionally, for large datasets, consider using hv․save(․․․, width=1200, height=800) to improve resolution!!!

Customizing plot aesthetics before export

Before calling hv․save, fine‑tune the visual style with HoloViews opts and Bokeh properties․ Use ․opts to set line colors, marker shapes, line widths, and alpha for transparency․ For example: plot = plot․opts(line_color=’darkgreen’, line_width=3, marker=’square’, marker_size=8, alpha=0․85)․ Add a title, subtitle, and axis labels via title, subtitle, xlabel, ylabel, and subtitle․ To improve readability, enable grid lines with grid=True, grid_line_color=’lightgray’, grid_line_alpha=0․5․ Position the legend with legend_position=’top_right’ or hide it with legend=False․ Adjust font sizes using title_text_font_size=’18pt’, xlabel_text_font_size=’14pt’, ylabel_text_font_size=’14pt’, and legend_text_font_size=’12pt’․ For categorical plots, set categorical_order to control the order of categories․ Use the plot․opts to set background_fill_color=’white’ and border_fill_color=’white’ to avoid unwanted borders․ If you need a dark theme, set background_fill_color=’#2e2e2e’, border_fill_color=’#2e2e2e’, and adjust text colors accordingly․ To include a hover tool, add tools=[‘hover’] and configure hover․tooltips to display relevant data; When exporting to PDF, ensure the resolution is high by specifying width and height in hv․save: hv․save(plot, ‘figure․pdf’, backend=’pdf’, width=1200, height=800)․ If the PDF appears blurry, increase the dpi parameter: hv․save(plot, ‘figure․pdf’, backend=’pdf’, dpi=300)․ Finally, to embed custom fonts, set font=’DejaVu Sans’ or provide a path to a ․ttf file with font_path․ These adjustments guarantee that the exported PDF matches the interactive notebook appearance․ Fine‑tuning these options ensures the PDF output matches the plot, keeping consistency now․

Exporting hvplot to PDF using hv․save

Use hv․save(plot, “file․pdf”, backend=”pdf”) to export․ Set width, height, dpi for clarity․ Example: hv․save(plot, “out․pdf”, backend=”pdf”, width=1200, height=800, dpi=300)․ This renders static PDF with all styles․ Use hv․save to generate PDF․ now

Syntax and parameters of hv․save for PDF

To export an hvplot figure to a PDF file, the hv․save function is employed․ The basic syntax is:

hv․save(plot, "output․pdf", backend="pdf")

The first argument is the HoloViews object (often the result of an hvplot call); The second is the destination path, which must end with ․pdf․ The backend keyword explicitly selects the PDF renderer; if omitted, the default renderer may produce a PNG or SVG instead․

Additional optional parameters allow fine‑tuning of the output:

  • width and height – set the figure dimensions in pixels․ Typical values range from 800–1200 for width and 600–900 for height․
  • dpi – controls the resolution; 300 dpi is common for print‑ready PDFs․
  • verbose – when True, prints progress messages to the console․
  • save_as – accepts a Path object or string; useful for dynamic file naming․
  • renderer – can be set to "pdf" or "svg" for vector outputs; "png" is not supported for PDF․
  • title – a string that will appear as the document title in the PDF metadata․
  • metadata – a dictionary of key/value pairs inserted into the PDF’s metadata stream․

Example with full customization:

hv․save(
 plot,
 "report․pdf",
 backend="pdf",
 width=1200,
 height=800,
 dpi=300,
 verbose=True,
 title="Annual Sales",
 metadata={"Author": "Data Team", "Subject": "Sales Report"}
)

When running in a Jupyter environment, ensure that the hvplot extension is loaded (hv․extension("bokeh")) and that the Bokeh server is accessible․ If the PDF appears blank, verify that the plot contains visible glyphs and that the backend is correctly set to "pdf"․ The resulting file is a self‑contained PDF that preserves vector graphics, making it ideal for high‑quality publications․

The PDF output can be refined by embedding custom CSS styles or applying HoloViews options such as hv․opts to adjust font sizes before calling hv․save․ This ensures consistency across figures and facilitates batch processing of datasets into a report․ Verify the final PDF with a viewer to confirm all elements render correctly․

Alternative PDF Export Techniques

Besides hv․save, users can employ Bokeh’s export_png and export_svgs to capture raster or vector snapshots, then convert PNGs to PDF with reportlab or Matplotlib’s PDF backend․ These methods bypass VPN restrictions and integrate into automated pipelines․

Using Bokeh’s export_png and export_svgs

When hvplot objects are rendered by Bokeh, the underlying Figure can be extracted via hvplot_obj․opts(․․․)․opts(․․․) and passed to Bokeh’s export_png or export_svgs․ export_png requires selenium and a headless browser; it renders the full canvas, including tooltips, into a PNG file․ export_svgs writes a pure SVG representation, preserving vector quality․ Both accept a filename and optional height and width․ After generating a PNG, convert it to PDF with reportlab or matplotlib․backends․backend_pdf․ For SVG, embed it into a PDF using svglib or cairosvg․ This workflow works when VPN blocks hv․save, as export functions use local rendering․ Batch‑process multiple hvplot figures by looping over a list of hvplot_obj instances, extracting each Figure, and saving sequentially․ Call output_file before rendering to ensure correct initialization․ The combination of export_png and export_svgs provides a robust fallback when hv․save fails․

In practice, verify that export_png dependencies are installed: pip install selenium webdriver-manager pillow․ Set up a headless Chrome instance by configuring webdriver․Chrome(options=chrome_options) with chrome_options․add_argument("--headless")․ For export_svgs, ensure svglib is available to convert SVG to PDF․ A typical conversion snippet: from svglib․svglib import svg2rlg; from reportlab․graphics import renderPDF; renderPDF․drawToFile(svg2rlg('plot․svg'), 'plot․pdf')․ This keeps vector fidelity, essential for publication‑grade figures․ When working in JupyterLab, display the intermediate PNG or SVG inline using IPython․display․Image or IPython․display․SVG to confirm rendering before committing to PDF․ Wrap the export logic in a function that accepts an hvplot object and a target PDF path, handling both PNG and SVG routes based on user preference or file size constraints․

Also, set export_png resolution via height and width to match final PDF dimensions․ Remember to clean temporary files after export to keep the workspace tidy․

Converting PNG to PDF with reportlab or matplotlib backend

After exporting an hvplot figure to PNG with Bokeh’s export_png, the image can be embedded into a PDF using either ReportLab or Matplotlib’s PDF backend․ With ReportLab, import canvas from reportlab․pdfgen and create a canvas object with the desired page size․ Use drawImage to place the PNG; specify width and height to match the original resolution or scale to fit the page․ Example:

from reportlab․pdfgen import canvas
c = canvas․Canvas("output․pdf", pagesize=letter)
c․drawImage("plot․png", 0, 0, width=600, height=400)
c․save

Matplotlib offers a lightweight alternative: load the PNG with imread, create a figure with figsize matching the image, and save using PdfPages․ This preserves vector elements if the PNG contains them, and allows adding annotations or titles before saving․ Example:

import matplotlib․pyplot as plt
from matplotlib․backends․backend_pdf import PdfPages
import matplotlib․image as mpimg
img = mpimg․imread("plot․png")
fig, ax = plt․subplots(figsize=(6,4))
ax․imshow(img)
ax․axis('off')
with PdfPages("output․pdf") as pdf:
 pdf․savefig(fig, bbox_inches='tight')
 pdf․close

Both methods handle large images efficiently; ReportLab is preferable for complex layouts, while Matplotlib is convenient for quick one‑page exports․ Ensure the PNG path is correct and that the PDF writer has write permissions in the target directory․ Clean up temporary PNG files after conversion to keep the workspace tidy․ Generate PNG at high DPI, then scale down in PDF to reduce file size while keeping fidelity․ This balances quality and performance for reports daily․

Troubleshooting Common Issues

VPN blocks local file writes during hvplot PDF export․ Verify Bokeh and hvplot versions match and run the notebook on a non‑VPN machine․ If the PDF is blank, ensure the PNG export path is correct and the image is not corrupted․ Use ReportLab for reliable PDF creation and DPI for clarity! use․ !

VPN connectivity problems during notebook export

When a corporate VPN is active, hvplot’s hv․save may silently fail to write the PDF because the underlying Bokeh export routines attempt to access local file descriptors that the VPN firewall blocks․ Users report that the notebook runs to completion but resulting file is empty․ The VPN can interfere with the temporary directory used by Bokeh to store PNG intermediates; if the temp path is redirected to a network share, write permissions may be revoked, causing hv․save to raise a silent exception․ A reliable workaround is to explicitly set the export path to a local directory exempt from VPN filtering, for example by using the environment variable BOKEH_OUTPUT_DIR or by passing filename= to hv․save․ Another trick is to disable the VPN for the duration of the export or to use a virtual machine that bypasses the corporate firewall․ Upgrading to the latest hvplot (≥0․4․0) and Bokeh (≥2․4) resolves many issues because newer releases include a fallback to the export_png function, which writes directly to disk without relying on the network stack․ Always verify that the temporary directory exists and is writable before running hv․save, and check the notebook’s output log for any “Permission denied” or “File not found” messages that indicate VPN‑related restrictions․ Additionally, setting the Bokeh output directory to a path such as /tmp or a folder can circumvent firewall restrictions․ Ensuring the export path is on a local filesystem is essential․ Logging the export process with logger can reveal permission errors․

Leave a Reply