Matplotlib Plotting
Matplotlib offers a wide range of plotting capabilities, from basic line plots to more complex charts. Below is a guide to common types of plots you can create using Matplotlib.
1. Line Plot
A line plot is one of the most basic types of plots. It displays data as a series of points connected by straight line segments.
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
# Create line plot
plt.plot(x, y)
# Add title and labels
plt.title("Simple Line Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
# Show plot
plt.show()
2. Scatter Plot
Scatter plots are used to visualize the relationship between two variables. Each point represents a pair of values.
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
# Create scatter plot
plt.scatter(x, y)
plt.title("Simple Scatter Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()
3. Bar Plot
Bar plots are useful for comparing quantities of different categories.
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 30]
# Create bar plot
plt.bar(categories, values)
plt.title("Simple Bar Plot")
plt.xlabel("Categories")
plt.ylabel("Values")
plt.show()
4. Histogram
Histograms show the distribution of a dataset by dividing it into bins (or intervals) and counting the number of points that fall into each bin.
data = [1, 1, 2, 2, 2, 3, 3, 4, 5, 6, 6, 6, 7]
# Create histogram
plt.hist(data, bins=5)
plt.title("Simple Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
5. Pie Chart
A pie chart displays data in a circular graph, with each wedge representing a proportion of the whole.
labels = ['Apples', 'Bananas', 'Cherries', 'Dates']
sizes = [25, 35, 25, 15]
# Create pie chart
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title("Simple Pie Chart")
plt.show()
6. Subplots
Subplots allow you to display multiple plots in the same figure. This is useful when you want to compare multiple visualizations.
# Data
x = [1, 2, 3, 4]
y = [10, 20, 30, 40]
# Create a figure with 2 rows and 1 column
plt.subplot(2, 1, 1)
plt.plot(x, y)
plt.title("Line Plot")
plt.subplot(2, 1, 2)
plt.bar(x, y)
plt.title("Bar Plot")
# Adjust layout and display
plt.tight_layout()
plt.show()
7. Stacked Bar Plot
A stacked bar plot shows multiple datasets stacked on top of each other. This is useful for comparing the total values while showing the contribution of each dataset.
import numpy as np
# Data
categories = ['A', 'B', 'C', 'D']
values1 = [3, 5, 2, 6]
values2 = [2, 3, 4, 1]
# Plot
plt.bar(categories, values1, label="Dataset 1")
plt.bar(categories, values2, bottom=values1, label="Dataset 2")
plt.title("Stacked Bar Plot")
plt.xlabel("Categories")
plt.ylabel("Values")
plt.legend()
plt.show()
8. Box Plot
Box plots (also called box-and-whisker plots) show the distribution of data based on a five-number summary: minimum, first quartile (Q1), median, third quartile (Q3), and maximum.
# Data
data = [np.random.normal(0, std, 100) for std in range(1, 4)]
# Create box plot
plt.boxplot(data, vert=True, patch_artist=True)
plt.title("Simple Box Plot")
plt.xlabel("Category")
plt.ylabel("Value")
plt.show()
9. Heatmap
A heatmap represents data as a matrix, with values represented by colors.
import numpy as np
# Data
data = np.random.rand(10, 10)
# Create heatmap
plt.imshow(data, cmap='hot', interpolation='nearest')
plt.title("Heatmap")
plt.colorbar() # Add a color bar to show the mapping of values to colors
plt.show()
10. Logarithmic Plot
For data that spans several orders of magnitude, you can apply logarithmic scaling to the axes.
x = np.linspace(1, 100, 100)
y = np.exp(x)
# Plot with logarithmic scaling
plt.plot(x, y)
plt.yscale('log')
plt.title("Logarithmic Scale Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis (log scale)")
plt.show()
Customizing Plots
Matplotlib allows for extensive customization. You can change colors, line styles, markers, add annotations, grids, and more:
- Line style and color:
plt.plot(x, y, linestyle='--', color='r', marker='o') - Adding gridlines:
plt.grid(True) - Adding annotations:
plt.annotate('Highest Point', xy=(4, 40), xytext=(3, 30), arrowprops=dict(facecolor='black', arrowstyle='->')) - Adjusting figure size:
plt.figure(figsize=(8, 6))
Saving Plots
You can save your plot as an image file using savefig():
plt.plot(x, y)
plt.savefig('plot.png', dpi=300)
Conclusion
Matplotlib provides a comprehensive set of tools for creating a wide variety of visualizations, from simple line plots to advanced plots like heatmaps and box plots. It offers powerful customization options to fine-tune your visualizations to suit your needs.