Matplotlib basics to advance topics with examples
Matplotlib is a versatile plotting library for creating static, interactive, and animated visualizations in Python. Let's go through the basics to advanced topics with explanations and examples.
Basics
1. Basic Plotting
Line Plot:
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [10, 20, 25, 30, 40] plt.plot(x, y) plt.xlabel('X-axis Label') plt.ylabel('Y-axis Label') plt.title('Basic Line Plot') plt.show()
Scatter Plot:
x = [1, 2, 3, 4, 5] y = [10, 20, 25, 30, 40] plt.scatter(x, y, color='red') plt.title('Basic Scatter Plot') plt.show()
Bar Plot:
categories = ['A', 'B', 'C', 'D'] values = [10, 24, 36, 40] plt.bar(categories, values) plt.title('Basic Bar Plot') plt.show()
2. Styling and Customization
Changing Line Styles and Colors:
plt.plot(x, y, linestyle='--', color='green', marker='o') plt.title('Line Plot with Custom Style') plt.show()
Adding Grid and Legends:
plt.plot(x, y, label='Line 1') plt.plot(x, [i * 2 for i in y], label='Line 2') plt.legend() plt.grid(True) plt.show()
Adjusting Figure Size:
plt.figure(figsize=(8, 4)) plt.plot(x, y) plt.title('Figure with Custom Size') plt.show()
Intermediate
3. Subplots
Creating Multiple Plots:
fig, axs = plt.subplots(2, 2) # 2x2 grid axs[0, 0].plot(x, y) axs[0, 0].set_title('Plot 1') axs[0, 1].scatter(x, y) axs[0, 1].set_title('Plot 2') axs[1, 0].bar(categories, values) axs[1, 0].set_title('Plot 3') axs[1, 1].hist(values) axs[1, 1].set_title('Plot 4') plt.tight_layout() plt.show()
4. Histograms
Creating a Histogram:
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] plt.hist(data, bins=4, color='blue', edgecolor='black') plt.title('Histogram') plt.show()
5. Pie Charts
Basic Pie Chart:
sizes = [20, 30, 25, 25] labels = ['A', 'B', 'C', 'D'] plt.pie(sizes, labels=labels, autopct='%1.1f%%') plt.title('Basic Pie Chart') plt.show()
Customizing Pie Chart:
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, explode=(0.1, 0, 0, 0)) plt.title('Customized Pie Chart') plt.show()
Advanced
6. Advanced Plot Customization
Adding Annotations:
plt.plot(x, y) plt.annotate('Highest Point', xy=(5, 40), xytext=(4, 30), arrowprops=dict(facecolor='black', arrowstyle='->')) plt.title('Line Plot with Annotation') plt.show()
Custom Ticks and Labels:
plt.plot(x, y) plt.xticks([1, 2, 3, 4, 5], ['One', 'Two', 'Three', 'Four', 'Five']) plt.yticks([10, 20, 30, 40]) plt.title('Plot with Custom Ticks') plt.show()
7. 3D Plotting
3D Line and Scatter Plots:
from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') z = [1, 2, 3, 4, 5] ax.plot(x, y, z) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.title('3D Line Plot') plt.show() # 3D Scatter Plot ax.scatter(x, y, z) plt.title('3D Scatter Plot') plt.show()
8. Seaborn Integration
Using Seaborn for Enhanced Visuals:
import seaborn as sns # Seaborn pairplot iris = sns.load_dataset('iris') sns.pairplot(iris, hue='species') plt.title('Seaborn Pairplot') plt.show() # Seaborn heatmap data = iris.corr() sns.heatmap(data, annot=True, cmap='coolwarm') plt.title('Seaborn Heatmap') plt.show()
9. Advanced Plots with Multiple Axes
Twin Axes:
fig, ax1 = plt.subplots() ax2 = ax1.twinx() # Create another axes sharing the same x-axis ax1.plot(x, y, 'g-') ax2.plot(x, [i ** 2 for i in y], 'b-') ax1.set_xlabel('X Data') ax1.set_ylabel('Y1', color='g') ax2.set_ylabel('Y2', color='b') plt.title('Twin Axes Plot') plt.show()
10. Animation
Creating Animations with FuncAnimation:
from matplotlib.animation import FuncAnimation fig, ax = plt.subplots() line, = ax.plot([], [], 'r-') def init(): ax.set_xlim(0, 2 * np.pi) ax.set_ylim(-1, 1) return line, def update(frame): x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x + frame) line.set_data(x, y) return line, ani = FuncAnimation(fig, update, frames=np.linspace(0, 2 * np.pi, 128), init_func=init, blit=True) plt.title('Sine Wave Animation') plt.show()
11. Interactive Plots with Widgets
Using ipywidgets for Interaction:
from ipywidgets import interact import numpy as np def plot_function(frequency=1.0): x = np.linspace(0, 2 * np.pi, 100) y = np.sin(frequency * x) plt.plot(x, y) plt.title(f'Sine Wave with Frequency {frequency}') plt.show() interact(plot_function, frequency=(0.1, 2.0, 0.1))
Examples Combining Techniques
Example 1: Customizing Subplots
fig, axs = plt.subplots(2, 2, figsize=(10, 6))
# Line plot
axs[0, 0].plot(x, y, linestyle='--', color='purple')
axs[0, 0].set_title('Custom Line Plot')
# Scatter plot with grid and annotations
axs[0, 1].scatter(x, y, color='red')
axs[0, 1].grid(True)
axs[0, 1].annotate('Point 1', xy=(1, 10), xytext=(2, 20),
arrowprops=dict(facecolor='black', arrowstyle='->'))
axs[0, 1].set_title('Scatter Plot with Annotations')
# Histogram with custom bins and colors
data = np.random.randn(100)
axs[1, 0].hist(data, bins=20, color='blue', edgecolor='black')
axs[1, 0].set_title('Histogram with Custom Bins')
# Pie chart
sizes = [30, 40, 20, 10]
labels = ['A', 'B', 'C', 'D']
axs[1, 1].pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)
axs[1, 1].set_title('Pie Chart')
plt.tight_layout()
plt.show()
Advanced Topics (Continued)
12. Customizing Color Maps
Using Built-in Color Maps:
import numpy as np # Generate some data data = np.random.rand(10, 10) # Display data using a color map plt.imshow(data, cmap='viridis') plt.colorbar() # Show a color scale plt.title('Heatmap with Viridis Color Map') plt.show()
Creating Custom Color Maps:
from matplotlib.colors import LinearSegmentedColormap # Define colors for the custom colormap colors = ['blue', 'white', 'red'] cmap = LinearSegmentedColormap.from_list('custom_cmap', colors) # Display data using the custom color map plt.imshow(data, cmap=cmap) plt.colorbar() plt.title('Heatmap with Custom Color Map') plt.show()
13. Contour Plots
Creating a Contour Plot:
x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = np.sin(np.sqrt(X**2 + Y**2)) plt.contour(X, Y, Z, levels=20, cmap='coolwarm') plt.colorbar() plt.title('Contour Plot') plt.show()
Filled Contour Plot:
plt.contourf(X, Y, Z, levels=20, cmap='viridis') plt.colorbar() plt.title('Filled Contour Plot') plt.show()
14. Plotting with Error Bars
Adding Error Bars to a Plot:
x = np.arange(0, 10, 1) y = np.sin(x) y_err = 0.2 plt.errorbar(x, y, yerr=y_err, fmt='-o', ecolor='red', capsize=5) plt.title('Plot with Error Bars') plt.show()
15. Logarithmic and Polar Plots
Logarithmic Scale:
x = np.linspace(0.1, 10, 100) y = np.exp(x) plt.plot(x, y) plt.xscale('log') plt.yscale('log') plt.title('Logarithmic Scale Plot') plt.show()
Polar Plot:
theta = np.linspace(0, 2 * np.pi, 100) r = np.abs(np.sin(2 * theta) * np.cos(2 * theta)) plt.polar(theta, r) plt.title('Polar Plot') plt.show()
16. Statistical Plots
Box Plot:
data = np.random.rand(100, 5) plt.boxplot(data) plt.title('Box Plot') plt.show()
Violin Plot:
plt.violinplot(data, showmeans=True) plt.title('Violin Plot') plt.show()
17. Saving Figures
Saving to File:
plt.plot(x, y) plt.title('Plot to Save') plt.savefig('plot.png') # Save as PNG plt.savefig('plot.pdf') # Save as PDF plt.show()
Controlling Output Quality:
plt.plot(x, y) plt.title('High-Resolution Plot') plt.savefig('high_res_plot.png', dpi=300) # Save with higher resolution plt.show()
Examples Combining Advanced Techniques
Example 2: Comprehensive Visualization
fig, ax = plt.subplots(figsize=(10, 6))
# Plot data with error bars
x = np.linspace(0, 10, 50)
y = np.sin(x)
y_err = 0.2
ax.errorbar(x, y, yerr=y_err, fmt='o', ecolor='gray', label='Sine with error bars')
# Adding annotations and customizing ticks
for i in range(0, 50, 5):
ax.annotate(f'({x[i]:.1f}, {y[i]:.1f})', (x[i], y[i]), textcoords="offset points", xytext=(0, 10), ha='center')
# Customize the plot with grid, title, labels, and legend
ax.set_title('Comprehensive Visualization Example', fontsize=16)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.grid(True)
ax.legend()
# Save the plot
plt.savefig('comprehensive_plot.png', dpi=300)
plt.show()
Example 3: Heatmap with Annotations
# Generate a heatmap with annotated values
data = np.random.rand(10, 10)
fig, ax = plt.subplots()
cax = ax.imshow(data, cmap='viridis')
# Annotate each cell in the heatmap
for i in range(data.shape[0]):
for j in range(data.shape[1]):
ax.text(j, i, f'{data[i, j]:.2f}', ha='center', va='center', color='white')
# Add colorbar and titles
fig.colorbar(cax)
ax.set_title('Heatmap with Annotations')
plt.show()
18. Interactive Plotting with mpl_toolkits
Zoomable and Panable Plots using
mpl_toolkits
and Widgets:from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Generate data for 3D scatter plot x = np.random.rand(100) y = np.random.rand(100) z = np.random.rand(100) scatter = ax.scatter(x, y, z, c='b', marker='o') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') ax.set_title('Interactive 3D Scatter Plot') plt.show()
Interactive Widgets with
%matplotlib notebook
in Jupyter Notebooks:%matplotlib notebook import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() x = np.linspace(0, 2*np.pi, 100) line, = ax.plot(x, np.sin(x)) # Interactive plot update def update_plot(phase, amplitude): line.set_ydata(np.sin(x + phase) * amplitude) fig.canvas.draw() from ipywidgets import interact interact(update_plot, phase=(0, 10, 0.1), amplitude=(0, 2, 0.1))
19. Advanced 3D Surface Plotting
Surface Plot with Contour Projections:
from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') 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)) # Surface plot surf = ax.plot_surface(X, Y, Z, cmap='viridis', edgecolor='none') fig.colorbar(surf) # Add contour projections ax.contour3D(X, Y, Z, 50, cmap='binary') ax.set_title('3D Surface Plot with Contours') plt.show()
20. Animation with FuncAnimation
Advanced Animation with Custom Functions:
import numpy as np from matplotlib.animation import FuncAnimation fig, ax = plt.subplots() x = np.linspace(0, 2*np.pi, 100) line, = ax.plot(x, np.sin(x)) def init(): ax.set_xlim(0, 2*np.pi) ax.set_ylim(-1.5, 1.5) return line, def update(frame): line.set_ydata(np.sin(x + frame)) return line, ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128), init_func=init, blit=True) plt.show()
21. Custom Legends and Annotations
Custom Legend Positioning:
x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) plt.plot(x, y1, label='Sine Wave') plt.plot(x, y2, label='Cosine Wave') # Customizing legend plt.legend(loc='upper right', fontsize='small', shadow=True, title='Waves', title_fontsize='medium') plt.title('Custom Legend Example') plt.show()
Advanced Annotations with Box Styling:
plt.plot(x, y1) plt.title('Advanced Annotation Example') # Adding an annotation with a custom style plt.annotate('Local Max', xy=(np.pi/2, 1), xytext=(np.pi/2 + 1, 1.5), arrowprops=dict(facecolor='black', shrink=0.05), bbox=dict(boxstyle='round,pad=0.3', edgecolor='blue', facecolor='lightyellow')) plt.show()
22. Advanced Data Visualization Techniques
Hexbin Plot for Density Estimation:
x = np.random.randn(1000) y = np.random.randn(1000) plt.hexbin(x, y, gridsize=30, cmap='Blues') plt.colorbar(label='Counts') plt.title('Hexbin Plot Example') plt.show()
Pair Plot with
seaborn
:import seaborn as sns iris = sns.load_dataset('iris') # Pair plot with kde (kernel density estimate) sns.pairplot(iris, kind='scatter', hue='species', diag_kind='kde') plt.suptitle('Pair Plot with KDE', y=1.02) plt.show()
Examples to Combine Techniques for Advanced Analysis
Example 4: Data Exploration with Custom Annotations and Complex Layouts
fig, axs = plt.subplots(2, 2, figsize=(12, 8))
# Line plot with custom annotation
axs[0, 0].plot(x, np.sin(x), label='Sine Wave')
axs[0, 0].annotate('Peak', xy=(np.pi/2, 1), xytext=(np.pi/2, 1.5),
arrowprops=dict(arrowstyle='->', lw=1.5, color='blue'),
bbox=dict(boxstyle='round,pad=0.3', color='yellow'))
axs[0, 0].set_title('Annotated Sine Wave')
axs[0, 0].legend()
# Filled contour plot with color bar
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
contour = axs[0, 1].contourf(X, Y, Z, cmap='viridis', levels=20)
fig.colorbar(contour, ax=axs[0, 1])
axs[0, 1].set_title('Filled Contour Plot')
# Heatmap with annotations
data = np.random.rand(10, 10)
heatmap = axs[1, 0].imshow(data, cmap='hot')
for i in range(data.shape[0]):
for j in range(data.shape[1]):
axs[1, 0].text(j, i, f'{data[i, j]:.2f}', ha='center', va='center', color='black')
fig.colorbar(heatmap, ax=axs[1, 0])
axs[1, 0].set_title('Heatmap with Annotations')
# Polar plot with grid and ticks
theta = np.linspace(0, 2*np.pi, 100)
r = np.abs(np.sin(theta) * np.cos(theta))
axs[1, 1].polar(theta, r, color='magenta')
axs[1, 1].set_title('Polar Plot with Grid')
plt.tight_layout()
plt.show()
Example 5: Combining Seaborn and Matplotlib for Enhanced Plots
import seaborn as sns
# Load dataset
tips = sns.load_dataset('tips')
# Create a Seaborn style plot using Matplotlib
fig, ax = plt.subplots(figsize=(10, 6))
sns.histplot(tips['total_bill'], bins=20, kde=True, color='green', ax=ax)
# Customize with Matplotlib
ax.set_title('Total Bill Distribution')
ax.set_xlabel('Total Bill')
ax.set_ylabel('Frequency')
# Adding annotation to show a specific feature
mean_total_bill = tips['total_bill'].mean()
ax.axvline(mean_total_bill, color='red', linestyle='--')
ax.text(mean_total_bill + 1, 20, f'Mean: {mean_total_bill:.2f}', color='red')
plt.show()
Subscribe to my newsletter
Read articles from NAGARAJU ALOORI directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
NAGARAJU ALOORI
NAGARAJU ALOORI
"As an Agricultural Engineering graduate with a strong foundation in data analysis, I am passionate about pursuing a career in data science. I am eager to work in a dynamic environment that supports both professional and personal growth. My goal is to leverage my analytical skills to derive actionable insights that align with company objectives. I am committed to driving innovation and efficiency while prioritizing organizational goals and contributing to overall success."