Location>code7788 >text

『Play Streamlit』--Integrating Matplotlib

Popularity:33 ℃/2024-12-18 03:17:13

SteamlitThere are some drawing components (such as line, bar, scatter, etc.), but they are rather simple.

respond in singingPythonTraditional visualization libraries are much less powerful than that.

This article describes how theStreamlit Apphit the nail on the headMatplotliblibrary to plot.

1. Functions

function is specialized for use in theSteamlitDisplayed in the applicationMatplotlib Plotted graphs.

This function is able to directly convert theMatplotlib Figureobject is rendered directly to the specified position on the page.

There are few parameters, mainly:

name (of a thing) typology clarification
fig Figure object Matplotlib Figure objects to be rendered
clear_figure bool Controls whether graphics are cleared after rendering
use_container_width bool Decide whether to use the width of the parent container to override the original width of the graphic

The most important thing isfigparameter, which is passed through theMatplotlib The regular drawing method for creating graphic objects.

That is, we draw the graphs without thinking at all about theStreamlitNormal useMatplotlibto draw.

Directly after drawing theMatplotlib(used form a nominal expression)figobject is passed to thefunction will do.

2. Matplotlib compatibility issues

in usingMatplotlib together withStreamlit When combining, some compatibility issues may be encountered.

Matplotlib Supports multipleBackend, if an error occurs during use, you can try to remove theBackendset toTkAgg

The specific settings are as follows:

  1. show (a ticket)~/.matplotlib/matplotlibrcfile, if it doesn't exist create a
  2. Add a line to the file above:backend: TkAgg

If it's a windows system, the file path above is changed to:C:\Users\%username%\.matplotlib\matplotlibrc

In addition.Matplotlib This can be problematic in a multi-threaded environment, as it does not have perfect support for threading itself.

When deploying and sharing applications, this issue may be more pronounced due to the possibility of concurrent users.

To solve this problem, it is recommended to use thecome and wrapMatplotlib The relevant code, as shown below:

from .backend_agg import RendererAgg
_lock = 

with _lock:
    ('sample figure')
    ([1,20,3,50])
    (fig)

3. Examples of use

The following two examples, simplified for real-world situations, demonstrate the effect of combining the two.

3.1 Simulated data analysis project

In this example, we use the function generates three columns of random data of different types containing theDataFrame

In the Data Analysis and Visualization section, different types of plotting operations are performed depending on the columns selected.

  • When selectingColumn1 maybeColumn2 When plotting bar graphs or histograms
  • When selectingColumn3 When you choose to drawColumn1 respond in singingColumn2 scatterplot of

This example mainly demonstrates theStreamlit together withMatplotlib Combine ease and interactivity in data exploration and analytical visualization.

import streamlit as st
import pandas as pd
import as plt
import seaborn as sns
import numpy as np

import matplotlib

# To display Chinese
["-serif"] = ["Microsoft YaHei Mono"]
["axes.unicode_minus"] = False


# Generating Random Data
@st.cache_data
def generate_data():
    # generating 100 classifier for objects in rows such as words 3 列的随机数据
    data = {
        "Column1": (1, 100, 100),
        "Column2": (50, 10, 100),
        "Column3": (["A", "B", "C"], 100),
    }
    return (data)


data = generate_data()

# Data exploration component
("Data Exploration")
(())

# Data Analysis and Visualization
("Data Analysis and Visualization")
# Select columns to analyze
selected_column = ("Select the columns to analyze", )

# utilization Matplotlib Plotting bar charts
if selected_column in ["Column1", "Column2"]:
    fig, ax = ()
    if selected_column == "Column1":
        (data=data, x=selected_column, ax=ax)
    else:
        (data=data, x=selected_column, kde=True, ax=ax)
    ax.set_title(f"{selected_column} Distribution")
    ax.set_xlabel(selected_column)
    ax.set_ylabel("quantities")
    (fig)

# Plotting Scatter Plots(in order to Column1 respond in singing Column2 e.g.)
elif selected_column == "Column3":
    if ("Show Scatterplot"):
        fig2, ax2 = ()
        (data["Column1"], data["Column2"])
        ax2.set_title("Column1 together with Column2 exclusionary rule")
        ax2.set_xlabel("Column1")
        ax2.set_ylabel("Column2")
        (fig2)

Running effects:

3.2 Analog data monitoring and reporting

In this sample data monitoring and reporting application, the data monitoring and reporting is done through theget_live_data function simulates the acquisition of real-time data (which can be replaced with real data acquisition logic in real applications).

New data is then continuously fetched and merged into the total dataset through a loop that then uses theMatplotlib Plot line graphs to show trends in data over time.

This builds a simple real-time data monitoring application. In actual business scenarios, such as monitoring server performance indicators, key data on production lines, etc., it allows the relevant personnel to visualize the changes in data in real time, detect anomalies in time and make decisions.

import streamlit as st
import as plt
import time
import random
import pandas as pd

import matplotlib

# To display Chinese
["-serif"] = ["Microsoft YaHei Mono"]
["axes.unicode_minus"] = False


# Simulate a function to get live data
def get_live_data().
    # This can be replaced with real data fetching logic, such as from a database or API.
    new_data = (
        {
            
            
        }
    )
    return new_data


# Initialize the data
data = (columns=["time", "value"])

# Real-time data monitoring application title
("Real-time data monitoring")

# Create a placeholder for updating the chart
chart_placeholder = ()

while True: # Create a placeholder for updating the chart.
    # Get new data
    new_data = get_live_data()
    # Merge the new data into the total
    data = ([data, new_data], ignore_index=True)

    # Plot the line graph using Matplotlib
    fig, ax = ()
    (data["time"], data["value"])
    ax.set_title("Real-time data trends")
    ax.set_xlabel("time")
    ax.set_ylabel("Value")
    ax.set_xticklabels(data["time"], rotation=45)

    # Update the chart in Streamlit
    chart_placeholder.pyplot(fig)

    # Update data at intervals (set to 2 seconds here)
    (2)

运行效果:

4. Summary

Streamlit together withMatplotlib The key point of integration is thatStreamlit Providing a convenient framework for building applications.Matplotlib Focusing on powerful drawing features, the two pass function is tightly linked.

The data processing flow can be started with theMatplotlib The graphic objects can be created flexibly in theStreamlit Integration into applications.

The advantages of their combination are also obvious, firstly, in terms of visualization efficiency, the ability to quickly bring theMatplotlib Plotted graphic embeddingStreamlit applications, reducing development time and code.

Second, in terms of interactivity, theStreamlit The rich set of interactive components can be used with theMatplotlib Graphical linkage, such as controlling the content or scope of graphical displays through buttons, sliders, etc., makes it easier for users to explore data.