Matplotlib is a popular Python library for creating static, animated, and interactive data visualizations in Python. Matplotlib provides a variety of functions and tools for creating 2D and 3D plots, histograms, bar plots, scatter plots, and more.
Here are some key features and examples of how to use Matplotlib:
## Basic Plotting
The core of Matplotlib is its `pyplot` module, which provides a simple interface for creating basic plots. Here’s an example of how to create a simple line plot using Matplotlib:
python
import matplotlib.pyplot as plt
# Create some data
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
# Create a line plot
plt.plot(x, y)
# Add labels and title
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Simple Line Plot")
# Show the plot
plt.show()
## Subplots
Matplotlib also provides a way to create multiple plots in a single figure, using the `subplots()` function. Here’s an example of how to create a figure with two subplots:
python
import matplotlib.pyplot as plt
# Create some data
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 2, 3, 4, 5]
# Create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(2, 1)
# Create a line plot in the first subplot
ax1.plot(x, y1)
ax1.set_xlabel("X")
ax1.set_ylabel("Y1")
ax1.set_title("Line Plot 1")
# Create a bar plot in the second subplot
ax2.bar(x, y2)
ax2.set_xlabel("X")
ax2.set_ylabel("Y2")
ax2.set_title("Bar Plot 2")
# Show the plot
plt.show()
## Advanced Plotting
Matplotlib also provides a variety of advanced features for customizing plots, including setting colors and styles, adding legends and annotations, and creating multi-panel plots and interactive plots using other libraries.
Here’s an example of how to create a scatter plot with custom colors and a legend using Matplotlib:
python
import matplotlib.pyplot as plt
import numpy as np
# Create some data
x = np.random.rand(100)
y = np.random.rand(100)
colors = np.random.rand(100)
# Create a scatter plot with custom colors and a legend
plt.scatter(x, y, c=colors, cmap="viridis")
plt.colorbar()
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with Custom Colors")
plt.show()
Overall, Matplotlib is a powerful and flexible library for creating a wide range of data visualizations in Python, and is widely used in a variety of fields, including data science, engineering, and finance.