Streamlit has revolutionized the way data scientists and developers create web applications in Python. Its simplicity and power make it an excellent choice for building data-driven apps. When it comes to visualizations, Streamlit offers built-in support for various charting libraries, including Matplotlib and Plotly. In this blog post, we'll explore how to integrate these popular visualization tools into your Streamlit apps, enhancing their visual appeal and interactivity.
Matplotlib is a widely-used plotting library in Python, known for its flexibility and extensive customization options. Let's start by integrating a simple Matplotlib chart into a Streamlit app.
First, make sure you have the necessary libraries installed:
pip install streamlit matplotlib
Now, let's create a basic line plot:
import streamlit as st import matplotlib.pyplot as plt import numpy as np def create_matplotlib_chart(): x = np.linspace(0, 10, 100) y = np.sin(x) fig, ax = plt.subplots() ax.plot(x, y) ax.set_title('Sine Wave') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') return fig st.title('Matplotlib in Streamlit') st.pyplot(create_matplotlib_chart())
In this example, we define a function create_matplotlib_chart()
that generates a simple sine wave plot using Matplotlib. We then use st.pyplot()
to display the chart in our Streamlit app.
While Matplotlib isn't inherently interactive, we can add some basic interactivity using Streamlit's widgets. Let's modify our example to allow users to adjust the frequency of the sine wave:
import streamlit as st import matplotlib.pyplot as plt import numpy as np def create_interactive_matplotlib_chart(frequency): x = np.linspace(0, 10, 100) y = np.sin(frequency * x) fig, ax = plt.subplots() ax.plot(x, y) ax.set_title(f'Sine Wave (Frequency: {frequency})') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') return fig st.title('Interactive Matplotlib in Streamlit') frequency = st.slider('Frequency', 0.1, 5.0, 1.0, 0.1) st.pyplot(create_interactive_matplotlib_chart(frequency))
Now, users can adjust the frequency of the sine wave using a slider, and the chart updates in real-time.
Plotly is another powerful visualization library that offers interactive charts out of the box. Let's see how we can integrate Plotly into our Streamlit app.
First, install the required libraries:
pip install streamlit plotly
Now, let's create a simple scatter plot using Plotly:
import streamlit as st import plotly.graph_objects as go import numpy as np def create_plotly_chart(): x = np.random.randn(100) y = np.random.randn(100) fig = go.Figure(data=go.Scatter(x=x, y=y, mode='markers')) fig.update_layout(title='Random Scatter Plot', xaxis_title='X-axis', yaxis_title='Y-axis') return fig st.title('Plotly in Streamlit') st.plotly_chart(create_plotly_chart())
In this example, we create a random scatter plot using Plotly's go.Scatter
and display it using st.plotly_chart()
.
Plotly charts are inherently interactive, allowing users to zoom, pan, and hover over data points. Let's create a more complex example that showcases Plotly's interactive features:
import streamlit as st import plotly.graph_objects as go import numpy as np def create_interactive_plotly_chart(num_points, chart_type): x = np.linspace(0, 10, num_points) y = np.sin(x) if chart_type == 'Scatter': trace = go.Scatter(x=x, y=y, mode='markers') elif chart_type == 'Line': trace = go.Scatter(x=x, y=y, mode='lines') else: trace = go.Bar(x=x, y=y) fig = go.Figure(data=trace) fig.update_layout(title=f'{chart_type} Plot of Sine Wave', xaxis_title='X-axis', yaxis_title='Y-axis') return fig st.title('Interactive Plotly in Streamlit') num_points = st.slider('Number of Points', 10, 1000, 100) chart_type = st.selectbox('Chart Type', ['Scatter', 'Line', 'Bar']) st.plotly_chart(create_interactive_plotly_chart(num_points, chart_type))
This example allows users to adjust the number of data points and switch between different chart types. The resulting Plotly chart is fully interactive, providing a rich user experience.
In some cases, you might want to use both Matplotlib and Plotly in the same Streamlit app. Here's an example of how you can do that:
import streamlit as st import matplotlib.pyplot as plt import plotly.graph_objects as go import numpy as np def create_matplotlib_chart(): x = np.linspace(0, 10, 100) y = np.cos(x) fig, ax = plt.subplots() ax.plot(x, y) ax.set_title('Cosine Wave (Matplotlib)') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') return fig def create_plotly_chart(): x = np.linspace(0, 10, 100) y = np.sin(x) fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines')) fig.update_layout(title='Sine Wave (Plotly)', xaxis_title='X-axis', yaxis_title='Y-axis') return fig st.title('Matplotlib and Plotly in Streamlit') col1, col2 = st.columns(2) with col1: st.pyplot(create_matplotlib_chart()) with col2: st.plotly_chart(create_plotly_chart())
This example creates a two-column layout, displaying a Matplotlib chart in the left column and a Plotly chart in the right column.
Performance: For large datasets, consider using Plotly's go.Scattergl
for improved rendering performance.
Customization: Explore the extensive customization options offered by both Matplotlib and Plotly to create visually appealing charts that match your app's design.
Responsive Design: Use Streamlit's layout options (e.g., st.columns()
) to create responsive designs that work well on different screen sizes.
Caching: For computationally expensive chart generation, use Streamlit's @st.cache
decorator to improve app performance.
Consistency: Try to maintain a consistent style across your visualizations, whether you're using Matplotlib, Plotly, or a combination of both.
By integrating Matplotlib and Plotly into your Streamlit apps, you can create powerful, interactive data visualizations that engage your users and effectively communicate your insights. Experiment with different chart types, customization options, and interactivity features to find the perfect visualization solution for your specific use case.
15/11/2024 | Python
08/12/2024 | Python
06/12/2024 | Python
06/10/2024 | Python
22/11/2024 | Python
25/09/2024 | Python
26/10/2024 | Python
26/10/2024 | Python
22/11/2024 | Python
17/11/2024 | Python
26/10/2024 | Python
15/11/2024 | Python