AYUDA DE PYTHON

Bokeh Python (Cómo funciona para desarrolladores)

Actualizado julio 1, 2024
Compartir:
The creation of interactive visualizations and their embedding into high-quality PDF publications can be accomplished with ease by integrating Bokeh Python with IronPDF for Python.

Easily shareable and embeddable into online apps, Bokeh is a robust Python framework for making high-quality, interactive infographics. In-depth data analysis and presentation can be greatly aided by the complicated graphs it can create, like bubble charts, box plots, and charts with error bars.

IronPDF is primarily a .NET library, but you can use it to enhance its capability. Through the utilization of Bokeh for visual representation and IronPDF for PDF generation, users can effectively include intricate and dynamic visual data into static PDF reports.

Creating visualizations with Bokeh, exporting these plots as images, and then using IronPDF to embed these images into PDF documents make up this integration procedure. This method combines the finest features of static document generation with interactive visualizations to enable data scientists, analysts, and developers to create comprehensive, aesthetically rich reports that are simple to distribute and review.

## What is Bokeh Python?

Bokeh Python offers a powerful plotting interface with its `plotting` import `figure` module, enabling users to create a wide range of interactive data visualizations. Its flexibility extends to layout management, where `layouts` import `row` and `layouts` import `gridplot` facilitates the arrangement of multiple plots seamlessly.

As an interactive visualization library optimized for modern web browsers, Bokeh renders stunning bokeh plotting that dynamically responds to user interactions. From simple line charts to complex bar charts, Bokeh excels in conveying data points with clarity and precision, making it an invaluable tool for interactive data visualization, exploration, and presentation.

![Bokeh Python (How It Works For Developers): Figure 1](/static-assets/pdf/blog/bokeh-python/bokeh-python-1.webp)

Bokeh is appropriate for a variety of data science and visualization jobs because of its broad selection of plot styles, which include line charts, bar charts, scatter plots, box plots, bubble charts, and charts with error bars. Because of the library's high degree of customization, users can alter plot elements like colors, labels, and legends to produce visually appealing and educational images.

### Interactive Plots

Bokeh makes it possible to create interactive charts that let users explore data in greater depth by zooming, panning, and hovering over them. For deeper insights and data research, or even if you just want to plot publicly available data, this interactivity is essential.

### High-Quality Visuals

Bokeh creates visually stunning and high-quality visualizations that are appropriate for publication and presentation. The images are intended to be both educational and aesthetically pleasing.

### Customization

Bokeh provides a wide range of plot customization choices. Plot elements, colors, labels, and other features are all adjustable by the user, enabling customized and accurate displays.

### Server-Side Interactivity

Bokeh comes with an integrated Bokeh server that lets you create dynamic dashboards and online apps. This capability is perfect for dynamic data visualization needs because it allows for real-time data streaming and updating.

### Integration with Web Technologies

Bokeh visualizations can be exported as stand-alone HTML files or integrated into web apps. Sharing interactive visualizations on the internet is made simple by this connection.

### Widgets and Layouts

Bokeh facilitates the production of intricate layouts and interactive widgets (such as dropdown menus and sliders) that allow for the creation of sophisticated data dashboards and apps.

### Large Dataset Handling

Big datasets can be handled effectively by Bokeh. Even with large volumes of data, it makes use of effective rendering algorithms to maintain the responsiveness and interactivity of the visualizations.

## Create and Configure Bokeh Python

From installation to interactive plot generation, there are multiple steps involved in setting up and configuring Bokeh in Python.

### Install Bokeh

You must install the Bokeh library first. Pip can be used for this:

```sh
pip install bokeh

Importar bibliotecas Bokeh

Después de instalar Bokeh, debe importar las piezas necesarias de Bokeh.

from bokeh.plotting import figure, output_file, show
PYTHON

Preparar los datos y crear un gráfico

Prepara la información para su visualización. Estos datos pueden presentarse como Pandas DataFrames, NumPy arrays, o listas. La función figure de Bokeh puede utilizarse para crear un nuevo gráfico. La personalización de la parcela incluye el cambio de las etiquetas, títulos y otros detalles de la parcela.

# Sample data
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]

# Create a Bokeh figure
p = figure(title="Simple Bokeh Plot", x_axis_label='X-Axis', y_axis_label='Y-Axis')
PYTHON

Añadir renderizadores

Para representar sus datos, añada renderizadores (como líneas, círculos y barras) a la trama.

# Add a line renderer
p.line(x, y, legend_label="Line Example", line_width=2)
PYTHON

Configurar salida

Indique la ubicación de salida deseada para la parcela. Puede verse en línea o exportarse a un archivo.

# Output to an HTML file
output_file("bokeh_plot.html")
PYTHON

Mostrar la parcela

Utilice la función de visualización para representar los trazados Bokeh.

# Show the plot
show(p)
PYTHON

Primeros pasos

Crear visualizaciones interactivas utilizando Bokeh, exportarlas como fotos estáticas y luego producir un documento PDF con estas imágenes son los pasos necesarios para integrar Bokeh con IronPDF en Python. Utilizaremos la librería de Python IronPDF para construir el documento PDF.

¿Qué es IronPDF?

Utilice la robusta biblioteca IronPDF for Python para crear, modificar y convertir archivos PDF. Permite a los programadores trabajar con PDF existentes, convertir HTML en PDF y realizar diversas tareas de programación asociadas a los PDF. IronPDF ofrece una forma ajustable y fácil de usar de crear documentos PDF de alta calidad, lo que lo convierte en una solución útil para aplicaciones que requieren la generación y el procesamiento dinámicos de PDF.

Bokeh Python (Cómo funciona para desarrolladores): Figura 2

Convertir HTML a PDF

Puede utilizar IronPDF para convertir información HTML en documentos PDF. Esto permite aprovechar HTML5, CSS3 y JavaScript contemporáneos para crear publicaciones PDF visualmente atractivas a partir de contenido web.

Creación y edición de PDF

A los nuevos documentos PDF creados mediante programación se les puede añadir texto, imágenes, tablas y otros materiales. IronPDF permite abrir y editar documentos PDF existentes. Puede añadir o modificar el contenido del PDF, así como eliminar secciones concretas.

Estilización y diseño avanzados

Utilice CSS para dar estilo al contenido de los PDF. Esto incluye la compatibilidad con diseños complejos, fuentes, colores y otros elementos de diseño. Cree material dinámico en PDF mediante la representación de contenido HTML que puede utilizarse con JavaScript.

Instalar IronPDF

Pip puede utilizarse para instalar IronPDF. Para instalarlo, utilice el siguiente comando:

pip install ironpdf

Generar documento PDF con gráficos Bokeh

Haz un gráfico utilizando Bokeh. Hagamos un gráfico lineal básico para ilustrarlo.

# Step 1: Import Bokeh Libraries
from bokeh.plotting import figure, output_file, show
from ironpdf import ChromePdfRenderer

# Prepare Your Data
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]

# Create a Plot
p = figure(title="Simple Bokeh Plot", x_axis_label='X-Axis', y_axis_label='Y-Axis')

# Add Renderers
p.line(x, y, legend_label="Line Example", line_width=2)

# Configure Output
output_file("bokeh_plot.html")

# Create a PDF document
iron_pdf = ChromePdfRenderer()

# Add HTML content to the PDF (you can also add text, CSS, or JavaScript)
pdf = iron_pdf.RenderHtmlFileAsPdf("bokeh_plot.html")

# Save the PDF document
pdf.SaveAs("BokehPlot.pdf")

print("PDF document generated successfully.")
PYTHON

Importamos las funciones necesarias de Bokeh. Establezca los valores de los datos de muestra del gráfico y produzca una figura Bokeh con etiquetas de eje y un título. A continuación, utilice p.line() para añadir un renderizador de líneas al gráfico. Utilice output_file de Bokeh()` método para exportar el gráfico Bokeh como archivo HTML, o imagen (como un PNG).

El archivo_de_salida()la función es importada de Bokeh. El gráfico Bokeh también puede exportarse como archivo HTML utilizando el nombre de archivo indicado. Cree un documento PDF con IronPDF e inserte en él el gráfico Bokeh exportado.

De IronPDF, importamos la clase ChromePdfRenderer. Iniciamos una nueva instancia de IronPDF. Uso de RenderHtmlFileAsPdf(), añadimos el archivo HTML del gráfico Bokeh exportado al documento PDF. Por último, utilizamos SaveAs() para guardar el documento PDF.

Bokeh Python (Cómo funciona para desarrolladores): Figura 3

Conclusión

En conclusión, aunque Bokeh Python y IronPDF no están directamente integrados, podemos lograr una funcionalidad comparable exportando gráficos Bokeh como imágenes y utilizando IronPDF para incrustarlos en documentos PDF. Mientras que IronPDF proporciona a Python capacidades programáticas para crear documentos PDF, Bokeh ofrece sólidas herramientas para crear gráficos dinámicos y vistosos.

Puede añadir fácilmente gráficos Bokeh a sus informes y documentos PDF siguiendo las instrucciones indicadas. Esto permite producir textos minuciosos y estéticamente agradables con una visualización de datos interactiva y dinámica que mejora la forma de presentar y comunicar los conocimientos basados en datos.

Al incluir los productos IronPDF y Iron Software en su pila de desarrollo, puede asegurarse de que sus clientes y usuarios finales reciban soluciones de software de gama alta y ricas en funciones. Además, esto ayudará a optimizar procesos y proyectos.

Con una documentación exhaustiva, una comunidad activa y actualizaciones periódicas, IronPDF es una gran herramienta para tener a mano. IronPDF ofrece una versión de prueba gratuita y precios a partir de 749 dólares, para que pueda seguir sacando el máximo partido a este producto. Iron Software es un socio fiable para proyectos modernos de desarrollo de software.

< ANTERIOR
Plotly Python (Cómo funciona para desarrolladores)

¿Listo para empezar? Versión: 2024.8 acaba de salir

Instalación pip gratuita View Licenses >