Introduction
Matplotlib and Seaborn are Python’s most popular plotting libraries — and they work great in Streamlit. This post shows how to render charts, style them, and when to use Plotly instead.
Step 1: Basic Matplotlib
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x), label="sin(x)")
ax.plot(x, np.cos(x), label="cos(x)")
ax.set_title("Trigonometric Functions")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
ax.grid(True, alpha=0.3)
st.pyplot(fig)
st.pyplot(fig) renders the figure. Always pass the fig object (don’t rely on global state).
Step 2: Seaborn
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv("data.csv")
fig, ax = plt.subplots(figsize=(10, 6))
sns.barplot(data=df, x="category", y="value", hue="group", ax=ax)
ax.set_title("Values by Category")
plt.xticks(rotation=45)
st.pyplot(fig)
Seaborn builds on Matplotlib — same st.pyplot(fig) call.
Step 3: Styling tips
# Use a style
plt.style.use("seaborn-v0_8-whitegrid") # or "ggplot", "dark_background"
# Set figure size
fig, ax = plt.subplots(figsize=(10, 6))
# Tight layout
plt.tight_layout()
# Custom colors
ax.plot(x, y, color="#3b82f6", linewidth=2, marker="o", markersize=4)
Step 4: Multiple subplots
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
axes[0].plot(x, np.sin(x))
axes[0].set_title("Sine")
axes[1].plot(x, np.cos(x))
axes[1].set_title("Cosine")
axes[2].plot(x, np.tan(x))
axes[2].set_title("Tangent")
plt.tight_layout()
st.pyplot(fig)
Step 5: Heatmaps
import seaborn as sns
import matplotlib.pyplot as plt
corr = df.corr()
fig, ax = plt.subplots(figsize=(8, 6))
sns.heatmap(corr, annot=True, cmap="coolwarm", center=0, ax=ax)
ax.set_title("Correlation Matrix")
st.pyplot(fig)
Step 6: Distribution plots
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
sns.histplot(df["value"], kde=True, ax=axes[0])
axes[0].set_title("Histogram")
sns.boxplot(data=df, x="category", y="value", ax=axes[1])
axes[1].set_title("Box Plot")
plt.tight_layout()
st.pyplot(fig)
Step 7: Save and download
import io
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight")
buf.seek(0)
st.download_button("📥 Download chart", data=buf, file_name="chart.png", mime="image/png")
Matplotlib vs Plotly in Streamlit
| Matplotlib/Seaborn | Plotly | |
|---|---|---|
| Interactivity | Static (no hover/zoom) | Interactive (hover, zoom, pan) |
| Ease of use | Familiar, extensive | Moderate learning curve |
| Chart types | Everything | Most things |
| Performance | Fast (PNG render) | Slower (JS rendering) |
| Customization | Unlimited | Good |
| Best for | Static reports, publications | Dashboards, exploration |
Rule: Use Plotly for interactive dashboards. Use Matplotlib/Seaborn for static reports, publications, and when you need a specific chart type Plotly doesn’t have.
Common mistakes
- Not passing
figtost.pyplot— relies on global state, breaks with multiple charts. - Forgetting
plt.close()— memory leak in loops. Usest.pyplot(fig)which auto-closes, or callplt.close(fig). - Too many charts — each
st.pyplotrenders a PNG. 10+ charts on a page is slow. - Not setting figure size — default is too small. Use
figsize=(10, 6). - Ignoring DPI — low DPI looks blurry. Use
dpi=150or higher.
Key Concepts
st.pyplot(fig)= render a Matplotlib figurefig, ax = plt.subplots()= create figure and axes- Seaborn = statistical plots on top of Matplotlib
bbox_inches="tight"= prevent label clippingio.BytesIO= in-memory buffer for downloads
What to Try Next
- Replace Matplotlib with Plotly for interactivity.
- Use Seaborn for statistical analysis visualizations.
- Add caching to expensive plot computations.
- Combine with theming for branded charts.
FAQ
Matplotlib vs Seaborn — which to use?
Seaborn is built on Matplotlib and is better for statistical plots (distributions, correlations, categorical). Matplotlib is lower-level and more flexible. Use Seaborn for stats; Matplotlib for custom plots.
Can I make Matplotlib charts interactive in Streamlit?
Not natively. Matplotlib is static (PNG). For interactivity, use Plotly. Alternatively, use mpld3 to convert Matplotlib to interactive D3, but it’s buggy.
How do I reduce chart rendering time?
Use st.cache_data to cache the data, not the figure. Keep figure sizes reasonable (10x6). Avoid 3D plots (slow). Use st.pyplot(fig, clear_figure=True) to free memory.