Data Visualization with Matplotlib, Seaborn, and Plotly

This tutorial introduces three popular Python libraries for data visualization: Matplotlib, Seaborn, and Plotly. We’ll cover their basic and advanced usage, key features, and provide examples to create various types of plots. Each section includes code snippets to help you get started.

Prerequisites

  • Basic Python knowledge

  • Install required libraries:

    pip install matplotlib seaborn plotly pandas numpy

1. Matplotlib

Matplotlib is a versatile library for creating static, animated, and interactive visualizations in Python. It’s highly customizable and widely used for basic and advanced plotting. This section covers both fundamental and advanced features.

Key Features

  • Supports line plots, scatter plots, bar charts, histograms, and more
  • Highly customizable (colors, labels, styles, etc.)
  • Integrates well with NumPy and Pandas
  • Advanced Features:
    • Subplot grids for multiple plots
    • 3D plotting with mpl_toolkits.mplot3d
    • Custom annotations and text
Code
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# Data for basic plots
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Line plot
plt.figure(figsize=(8, 6))
plt.plot(x, y, label='sin(x)', color='blue', linestyle='--')
plt.title('Sine Wave')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.legend()
plt.grid(True)
plt.show()

# Scatter plot
x_scatter = np.random.rand(50)
y_scatter = np.random.rand(50)
plt.scatter(x_scatter, y_scatter, color='red', marker='o')
plt.title('Random Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

# Advanced: 3D Surface Plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
Z = np.sin(np.sqrt(X**2 + Y**2))
surf = ax.plot_surface(X, Y, Z, cmap='viridis')
fig.colorbar(surf, label='Z value')
ax.set_title('3D Surface Plot')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()

Advanced Matplotlib Features

  • Subplot Grids: Use plt.subplots(nrows, ncols) to create multiple plots in a grid layout.
  • Annotations: Add text or arrows with plt.annotate() for highlighting specific data points.
  • Custom Styles: Use plt.style.use('ggplot') or other styles for different aesthetics.
  • 3D Plotting: Leverage mpl_toolkits.mplot3d for 3D visualizations like surface plots or wireframes.
Code
plt.style.use('ggplot')
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
x = np.linspace(0, 10, 100)
axs[0, 0].plot(x, np.sin(x), 'b-')
axs[0, 0].set_title('Sine')
axs[0, 1].plot(x, np.cos(x), 'r-')
axs[0, 1].set_title('Cosine')
axs[1, 0].plot(x, np.tan(x), 'g-')
axs[1, 0].set_title('Tangent')
axs[1, 1].plot(x, np.exp(x), 'm-')
axs[1, 1].set_title('Exponential')
axs[1, 1].annotate('Exp growth', xy=(8, np.exp(8)), xytext=(6, 500),
                   arrowprops=dict(facecolor='black', shrink=0.05))
plt.tight_layout()
plt.show()

Notes

  • Use plt.figure(figsize=(width, height)) to set the figure size.
  • Customize plots with parameters like color, linestyle, and marker.
  • Save plots using plt.savefig('filename.png').

2. Seaborn

Seaborn is built on top of Matplotlib and provides a high-level interface for creating attractive and informative statistical graphics. It integrates seamlessly with Pandas DataFrames.

Key Features

  • Simplified syntax for complex plots (e.g., heatmaps, violin plots)
  • Built-in themes for better aesthetics
  • Excellent for statistical visualizations
  • Advanced Features:
    • Pair plots for multivariate analysis
    • Facet grids for multi-panel plots
    • Clustered heatmaps with dendrograms
Code
import seaborn as sns
import pandas as pd
import numpy as np

# Sample data
data = pd.DataFrame({
    'Category': ['A', 'A', 'B', 'B', 'C', 'C'] * 10,
    'Value': np.random.randn(60)
})

# Box plot
sns.boxplot(x='Category', y='Value', data=data)
plt.title('Box Plot of Values by Category')
plt.show()

# Heatmap
matrix = np.random.rand(10, 10)
sns.heatmap(matrix, annot=True, cmap='coolwarm')
plt.title('Random Heatmap')
plt.show()

# Advanced: Pair Plot with Iris Dataset
iris = sns.load_dataset('iris')
sns.pairplot(iris, hue='species', diag_kind='kde')
plt.suptitle('Pair Plot of Iris Dataset', y=1.02)
plt.show()

Advanced Seaborn Features

  • FacetGrid: Create multi-panel plots based on categorical variables with sns.FacetGrid.
  • Clustermap: Generate hierarchical clustering heatmaps with sns.clustermap.
  • Regression Plots: Use sns.lmplot or sns.regplot for regression analysis with confidence intervals.
Code
tips = sns.load_dataset('tips')
g = sns.FacetGrid(tips, col='time', row='smoker')
g.map(sns.scatterplot, 'total_bill', 'tip')
g.add_legend()
plt.show()

Notes

  • Seaborn’s set_style() function (e.g., sns.set_style('darkgrid')) changes the plot theme.
  • Use annot=True in heatmaps to display values.
  • Seaborn works best with Pandas DataFrames for data manipulation.

3. Plotly

Plotly is a library for creating interactive, web-based visualizations. It’s ideal for dashboards and applications where user interaction (e.g., zooming, hovering) is desired.

Key Features

  • Interactive plots (zoom, pan, hover)
  • Supports a wide range of chart types (3D, geographic, etc.)
  • Works well in Jupyter notebooks and web applications
  • Advanced Features:
    • 3D scatter and surface plots
    • Geographic maps with plotly.express.choropleth
    • Animated plots for time-series data
Code
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np

# Sample data
df = pd.DataFrame({
    'x': np.linspace(0, 10, 100),
    'y': np.cos(x)
})

# Interactive line plot
fig = px.line(df, x='x', y='y', title='Cosine Wave')
fig.show()

# Bar chart
categories = ['A', 'B', 'C']
values = [10, 20, 15]
fig = go.Figure(data=[
    go.Bar(x=categories, y=values)
])
fig.update_layout(title='Bar Chart Example', xaxis_title='Category', yaxis_title='Value')
fig.show()

# Advanced: 3D Scatter Plot
df_3d = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100),
    'z': np.random.randn(100),
    'category': np.random.choice(['A', 'B', 'C'], 100)
})
fig = px.scatter_3d(df_3d, x='x', y='y', z='z', color='category', title='3D Scatter Plot')
fig.show()

Advanced Plotly Features

  • Geographic Maps: Use px.choropleth or px.scatter_geo for map-based visualizations.
  • Animations: Create animated plots with px.scatter or px.line using the animation_frame parameter.
  • Subplots: Use make_subplots from plotly.subplots for complex layouts.
Code
df_time = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100),
    'time': np.repeat(np.arange(10), 10),
    'category': np.random.choice(['A', 'B'], 100)
})
fig = px.scatter(df_time, x='x', y='y', color='category', animation_frame='time',
                 title='Animated Scatter Plot', range_x=[-3, 3], range_y=[-3, 3])
fig.show()

Notes

  • Use plotly.express for quick plots with minimal code.
  • Use plotly.graph_objects for more control over plot customization.
  • Save interactive plots as HTML using fig.write_html('filename.html').

Comparing the Libraries

Feature/Library Matplotlib Seaborn Plotly
Ease of Use Moderate High High (with Express)
Interactivity Limited Limited High
Aesthetics Customizable Attractive defaults Modern and interactive
Best For Static plots, customization Statistical plots Interactive dashboards

Tips for Choosing a Library

  • Use Matplotlib for quick, customizable static plots, 3D visualizations, or when integrating with other scientific Python libraries.
  • Use Seaborn for statistical visualizations, pair plots, or facet grids with Pandas DataFrames.
  • Use Plotly for interactive plots, geographic maps, or animations, especially for web applications or presentations.

Conclusion

Matplotlib, Seaborn, and Plotly each have unique strengths, with advanced features like 3D plotting, facet grids, and interactive animations. By mastering these libraries, you can create a wide range of visualizations tailored to your needs. Experiment with the examples above and explore the official documentation for more advanced features: - Matplotlib: https://matplotlib.org - Seaborn: https://seaborn.pydata.org - Plotly: https://plotly.com/python