Example Usage

import zero_true as zt
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import io
import base64
import json
import pandas as pd
import warnings

# Use Agg backend for Matplotlib to avoid GUI issues
plt.switch_backend('Agg')

# Suppress matplotlib warnings about the GUI backend
warnings.filterwarnings("ignore", category=UserWarning, message="Starting a Matplotlib GUI outside of the main thread will likely fail.")

# Initialize state
zt_state = zt.state()

# Sample data for demonstration
data = {
  'Category': ['A', 'B', 'C', 'D'],
  'Values': [23, 17, 35, 29]
}

df = pd.DataFrame(data)

# Function to create Matplotlib component
def create_matplotlib_component():
  # Create a sample matplotlib figure
  fig, ax = plt.subplots()
  ax.bar(df['Category'], df['Values'])
  ax.set_title('Sample Matplotlib Bar Chart')
  ax.set_xlabel('Category')
  ax.set_ylabel('Values')

  # Save the figure to a BytesIO object without displaying the GUI
  buf = io.BytesIO()
  plt.savefig(buf, format='png')
  buf.seek(0)

  # Encode the image to base64 string
  image_base64 = base64.b64encode(buf.read()).decode('utf-8')
  image_src = f'data:image/png;base64,{image_base64}'

  # Create a Matplotlib component
  sample_matplotlib = zt.Matplotlib(
      id="sample_matplotlib",
      alt="Sample Matplotlib Bar Chart",  # Alternative text for the graph image
      height=400,                         # Height of the graph
      src=image_src,                      # Source URL of the image of the graph
      width=600                           # Width of the graph
  )

  return sample_matplotlib

# Create components
matplotlib_component = create_matplotlib_component()

layout = zt.Layout(columns=[
  zt.Column(components=[
      zt.Row(components=[matplotlib_component.id]),
  ])
])

Example Output

Overview

pydantic model zero_true.Matplotlib

The Matplotlib component allows for the seamless integration of matplotlib figures into web applications, displaying them as images. This is particularly useful for scientific, engineering, or statistical dashboards where graphical data visualization is crucial.

Users can specify the dimensions and alternative text for accessibility, enhancing the usability and presentation of complex data. The ability to generate these components dynamically from matplotlib figures makes it a powerful tool for real-time data analysis and reporting.

JSON Schema

Bellow are the various attributes you can assign to the component. Utlizing them can allow for modifications to the pre-created object.
zero_true.Matplotlib
Zero True Component

Methods

classmethod from_matplotlib: (id: str, figure: Figure, alt=None, width=None, height=None); Create a Matplotlib component from a matplotlib figure.