import zero_true as ztimport matplotlib.pyplot as pltimport plotly.graph_objects as goimport ioimport base64import jsonimport pandas as pdimport warnings# Use Agg backend for Matplotlib to avoid GUI issuesplt.switch_backend('Agg')# Suppress matplotlib warnings about the GUI backendwarnings.filterwarnings("ignore", category=UserWarning, message="Starting a Matplotlib GUI outside of the main thread will likely fail.")# Initialize statezt_state = zt.state()# Sample data for demonstrationdata = { 'Category': ['A', 'B', 'C', 'D'], 'Values': [23, 17, 35, 29]}df = pd.DataFrame(data)# Function to create Matplotlib componentdef 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 componentsmatplotlib_component = create_matplotlib_component()layout = zt.Layout(columns=[ zt.Column(components=[ zt.Row(components=[matplotlib_component.id]), ])])
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.