Skip to content

Python Plotting Tools

Python offers powerful libraries for data visualization, with Matplotlib serving as the foundation for most plotting needs and Seaborn providing high-level statistical visualizations. These tools enable you to create everything from simple line plots to complex statistical graphics.

Matplotlib

Matplotlib is the fundamental plotting library for Python, providing a comprehensive set of tools for creating static, animated, and interactive visualizations.

Basic Plotting Commands

Here's a tutorial covering the main plotting commands:

import matplotlib.pyplot as plt
import numpy as np

# Basic line plot
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(8, 6))
plt.plot(x, y, label='sin(x)', color='blue', linewidth=2)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Basic Line Plot')
plt.legend()
plt.grid(True)
plt.show()

# Scatter plot
x_scatter = np.random.randn(100)
y_scatter = np.random.randn(100)

plt.figure(figsize=(8, 6))
plt.scatter(x_scatter, y_scatter, alpha=0.7, s=50)
plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Scatter Plot')
plt.show()

# Bar plot
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]

plt.figure(figsize=(8, 6))
plt.bar(categories, values, color=['red', 'green', 'blue', 'orange'])
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Plot')
plt.show()

3D Plotting Example

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Create figure and 3D axis
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# Generate data
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
u, v = np.meshgrid(u, v)

# Sphere coordinates
x = np.cos(u) * np.sin(v)
y = np.sin(u) * np.sin(v)
z = np.cos(v)

# Create 3D surface plot
ax.plot_surface(x, y, z, cmap='viridis', alpha=0.8)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.set_title('3D Sphere Surface')
plt.show()

# 3D scatter plot example
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# Random 3D data
n = 100
x_3d = np.random.randn(n)
y_3d = np.random.randn(n)
z_3d = np.random.randn(n)

ax.scatter(x_3d, y_3d, z_3d, c=z_3d, cmap='plasma', s=50)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.set_title('3D Scatter Plot')
plt.show()

Subplot Example

import matplotlib.pyplot as plt
import numpy as np

# Create data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = np.exp(-x/5)

# Create figure with subplots
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 10))

# Plot 1: Sine wave
ax1.plot(x, y1, 'b-', linewidth=2)
ax1.set_title('Sine Wave')
ax1.set_xlabel('x')
ax1.set_ylabel('sin(x)')
ax1.grid(True)

# Plot 2: Cosine wave
ax2.plot(x, y2, 'r-', linewidth=2)
ax2.set_title('Cosine Wave')
ax2.set_xlabel('x')
ax2.set_ylabel('cos(x)')
ax2.grid(True)

# Plot 3: Tangent wave (limited y-range)
ax3.plot(x, np.clip(y3, -5, 5), 'g-', linewidth=2)
ax3.set_title('Tangent Wave (clipped)')
ax3.set_xlabel('x')
ax3.set_ylabel('tan(x)')
ax3.set_ylim(-5, 5)
ax3.grid(True)

# Plot 4: Exponential decay
ax4.plot(x, y4, 'purple', linewidth=2)
ax4.set_title('Exponential Decay')
ax4.set_xlabel('x')
ax4.set_ylabel('exp(-x/5)')
ax4.grid(True)

# Adjust layout and display
plt.tight_layout()
plt.show()

Seaborn

Seaborn is a statistical data visualization library built on top of Matplotlib. It provides a high-level interface for creating attractive and informative statistical graphics with less code.

Introduction to Seaborn

Seaborn excels at: - Statistical visualizations: Built-in support for regression plots, distribution plots, and categorical data - Beautiful defaults: Attractive color palettes and plot styles out of the box - DataFrame integration: Native support for pandas DataFrames - Complex plot types: Easy creation of multi-panel figures and complex statistical plots

Key Features and Examples

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Set seaborn style
sns.set_style("whitegrid")

# Create sample dataset
np.random.seed(42)
data = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100) + np.random.randn(100) * 0.5,
    'category': np.random.choice(['A', 'B', 'C'], 100),
    'value': np.random.exponential(2, 100)
})

# Distribution plot
plt.figure(figsize=(12, 4))

plt.subplot(1, 3, 1)
sns.histplot(data['value'], kde=True)
plt.title('Distribution with KDE')

# Box plot by category
plt.subplot(1, 3, 2)
sns.boxplot(x='category', y='value', data=data)
plt.title('Box Plot by Category')

# Scatter plot with regression line
plt.subplot(1, 3, 3)
sns.scatterplot(x='x', y='y', hue='category', data=data)
sns.regplot(x='x', y='y', data=data, scatter=False, color='black')
plt.title('Scatter Plot with Regression')

plt.tight_layout()
plt.show()

# Correlation heatmap
plt.figure(figsize=(8, 6))
correlation_matrix = data[['x', 'y', 'value']].corr()
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', center=0)
plt.title('Correlation Heatmap')
plt.show()

Seaborn's strength lies in its ability to quickly generate publication-ready statistical visualizations with minimal code, making it an essential tool for data analysis and exploration.