Advanced Plots with Matplotlib
Duration: 5 min
This module delves into advanced plotting techniques using Matplotlib, focusing on creating complex and informative visualizations. Understanding these techniques is crucial for effectively communicating data insights and making data-driven decisions.
Customizing Plot Aesthetics
Matplotlib allows extensive customization of plot aesthetics, including colors, line styles, markers, and labels. Customizing these elements can enhance the clarity and visual appeal of your plots, making them more effective for data presentation.
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]
# Create a plot
plt.plot(x, y, color='green', linestyle='--', marker='o', label='Data')
# Customize plot aesthetics
plt.title('Customized Plot', fontsize=16)
plt.xlabel('X-axis', fontsize=14)
plt.ylabel('Y-axis', fontsize=14)
plt.grid(True)
plt.legend()
# Display the plot
plt.show()A plot with a green dashed line, circular markers, and a legend labeled 'Data'. The plot has a title 'Customized Plot', x-axis labeled 'X-axis', y-axis labeled 'Y-axis', and a grid.Creating Subplots
Subplots allow you to display multiple plots within a single figure, enabling side-by-side comparisons and more comprehensive data visualization. Matplotlib provides flexible functions to create and arrange subplots.
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 a figure with two subplots
fig, axs = plt.subplots(2, 1, figsize=(8, 6))
# Plot sine function in the first subplot
axs[0].plot(x, y1, color='blue', label='Sine')
axs[0].set_title('Sine Function')
axs[0].legend()
# Plot cosine function in the second subplot
axs[1].plot(x, y2, color='red', label='Cosine')
axs[1].set_title('Cosine Function')
axs[1].legend()
# Adjust layout and display the figure
plt.tight_layout()
plt.show()💡 Tip: When creating subplots, use plt.tight_layout() to automatically adjust subplot parameters for a neat arrangement.
❓ Which parameter can be used to change the line color in a Matplotlib plot?
❓ What function is used to create a figure with multiple subplots in Matplotlib?