Chapter 4: Data Visualization / Lesson 19

Advanced Plotting

Advanced Plotting Techniques

Advanced plotting involves creating sophisticated visualizations that reveal deeper insights in your data. This includes customizing plots, combining multiple visualizations, and using advanced statistical plots.

Mastering advanced plotting techniques allows you to create publication-quality visualizations and communicate complex data relationships effectively.

Customizing Plot Appearance

Advanced plots require careful customization. Here's how to control every aspect:

customization.py
# Advanced Plot Customization import matplotlib.pyplot as plt import numpy as np # Sample data x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) # Create figure with custom size fig, ax = plt.subplots(figsize=(10, 6)) # Plot multiple lines with custom styling ax.plot(x, y1, label='sin(x)', linewidth=2, color='#22d3ee', linestyle='-') ax.plot(x, y2, label='cos(x)', linewidth=2, color='#a855f7', linestyle='--') # Customize axes ax.set_xlabel('X Axis', fontsize=12, fontweight='bold') ax.set_ylabel('Y Axis', fontsize=12, fontweight='bold') ax.set_title('Advanced Customized Plot', fontsize=14, fontweight='bold') # Add legend, grid, and limits ax.legend(loc='best', fontsize=10) ax.grid(True, alpha=0.3, linestyle=':') ax.set_xlim(0, 10) ax.set_ylim(-1.5, 1.5) plt.tight_layout() plt.show() print("Customized plot with multiple lines, legend, and styling")

Subplot Layouts

Creating complex layouts with multiple subplots:

subplot_layouts.py
# Advanced Subplot Layouts import matplotlib.pyplot as plt import numpy as np # Create complex layout: 2 rows, 2 columns fig = plt.figure(figsize=(12, 10)) # Method 1: Using subplot2grid for flexible layouts ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=2) ax2 = plt.subplot2grid((3, 3), (0, 2)) ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=3) ax4 = plt.subplot2grid((3, 3), (2, 0), colspan=3) print("Advanced subplot layout created:") print(" - Flexible grid positioning") print(" - Different sized subplots") print(" - Custom arrangement") # Method 2: Using GridSpec for precise control from matplotlib.gridspec import GridSpec gs = GridSpec(3, 3, figure=fig) ax5 = fig.add_subplot(gs[0, :]) # Full width top ax6 = fig.add_subplot(gs[1, :2]) # Left side ax7 = fig.add_subplot(gs[1, 2:]) # Right side print("\nGridSpec provides even more control over layout")

Statistical Plots

Advanced statistical visualizations reveal data distributions and relationships:

statistical_plots.py
# Advanced Statistical Plots import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd # Sample data with multiple groups np.random.seed(42) data = { 'value': np.concatenate([ np.random.normal(100, 15, 100), np.random.normal(120, 20, 100), np.random.normal(110, 18, 100) ]), 'group': ['A'] * 100 + ['B'] * 100 + ['C'] * 100 } df = pd.DataFrame(data) print("Advanced Statistical Plot Types:") print(" 1. Violin Plot: Shows distribution shape") print(" sns.violinplot(data=df, x='group', y='value')") print(" 2. Box Plot with Swarm: Shows individual points") print(" sns.boxplot(...) + sns.swarmplot(...)") print(" 3. Pair Plot: Shows all pairwise relationships") print(" sns.pairplot(df)") print(" 4. Joint Plot: Scatter + marginal distributions") print(" sns.jointplot(data=df, x='x', y='y')") print("\nData summary:") print(df.groupby('group')['value'].describe())

3D Plots

Three-dimensional visualizations for complex data:

3d_plots.py
# 3D Plotting from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np # Create 3D figure fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111, projection='3d') # Generate 3D data x = np.linspace(-5, 5, 50) y = np.linspace(-5, 5, 50) X, Y = np.meshgrid(x, y) Z = np.sin(np.sqrt(X**2 + Y**2)) print("3D Plot Types:") print(" 1. Surface Plot: ax.plot_surface(X, Y, Z)") print(" 2. Scatter 3D: ax.scatter(x, y, z)") print(" 3. Wireframe: ax.plot_wireframe(X, Y, Z)") print("\n3D plots help visualize complex relationships in high-dimensional data")

Exercise: Create Advanced Plots

Complete the exercise on the right side:

  • Task 1: Create a figure with 2x2 subplots
  • Task 2: Plot different chart types in each subplot (line, bar, scatter, histogram)
  • Task 3: Customize each plot with titles, labels, and colors
  • Task 4: Add a main title for the entire figure

Write your code to create these advanced multi-plot visualizations!

💡 Learning Tip

Practice is essential. Try modifying the code examples, experiment with different parameters, and see how changes affect the results. Hands-on experience is the best teacher!

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...