Files
2024-05-01 12:28:44 -06:00

152 lines
2.6 KiB
Markdown

For creating and manipulating complex data visualizations, `Matplotlib` is an indispensable Python library. It's widely used for generating plots, histograms, bar charts, scatterplots, and more, offering extensive customization options to make the visualizations as informative and appealing as possible. Below is a concise reference guide for common use cases with `Matplotlib`, formatted in Markdown syntax:
# `Matplotlib` Reference Guide
## Installation
```
pip install matplotlib
```
## Basic Plotting
### Importing Matplotlib
```python
import matplotlib.pyplot as plt
```
### Creating a Simple Plot
```python
# Prepare some data
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
# Plot data
plt.plot(x, y)
# Show plot
plt.show()
```
### Creating a Scatter Plot
```python
# Scatter plot
plt.scatter(x, y)
# Show plot
plt.show()
```
### Multiple Plots on Same Axes
```python
# Second set of data
x2 = [1, 2, 3, 4]
y2 = [30, 25, 20, 15]
# Plot data
plt.plot(x, y, label='First Line')
plt.plot(x2, y2, label='Second Line')
# Adding a legend
plt.legend()
# Show plot
plt.show()
```
## Customizing Plots
### Titles, Labels, and Legends
```python
plt.plot(x, y)
# Title
plt.title('My First Plot')
# Axis labels
plt.xlabel('X Axis Label')
plt.ylabel('Y Axis Label')
# Show plot
plt.show()
```
### Line Styles and Markers
```python
plt.plot(x, y, color='red', linestyle='--', marker='o', label='Data Points')
# Show plot
plt.show()
```
### Setting Axis Ranges
```python
plt.plot(x, y)
# Setting the range for the axes
plt.xlim(0, 5)
plt.ylim(5, 35)
# Show plot
plt.show()
```
### Adding Grid Lines
```python
plt.plot(x, y)
# Adding grid
plt.grid(True)
# Show plot
plt.show()
```
## Other Types of Plots
### Histograms
```python
data = [1, 2, 2, 3, 3, 3, 4, 4, 5]
# Create histogram
plt.hist(data, bins=5, alpha=0.5, color='blue')
# Show plot
plt.show()
```
### Bar Charts
```python
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 5]
# Create bar chart
plt.bar(categories, values)
# Show plot
plt.show()
```
### Pie Charts
```python
slices = [7, 2, 2, 13]
categories = ['A', 'B', 'C', 'D']
# Create pie chart
plt.pie(slices, labels=categories, autopct='%1.1f%%')
# Show plot
plt.show()
```
## Saving Figures
```python
plt.plot(x, y)
# Save the figure
plt.savefig('plot.png')
# Show plot
plt.show()
```
`Matplotlib` is a powerful library for creating static, interactive, and animated visualizations in Python. This guide covers the basics of generating and customizing plots, but Matplotlib's functionality is vast, supporting a wide range of plot types and customization options to suit various data visualization needs.