**Getting Started**

This is a comprehensive tutorial and may take time to finish reading.

If you are in a hurry, you can check a quick tutorial: Visualizing Data with Matplotlib: Beginner’s Guide

**Installation of Matplotlib**

Before we can create any plots, we need to install Matplotlib.

It’s as simple as running a command in your terminal or command prompt:

`pip install matplotlib`

**Importing the Library**

**Library**: A collection of functions and methods that allows you to perform actions without writing your code.**Import**: Bringing in a library or a portion of it to use in your code.

Once installed, you need to import it into your Python script to start using it. Here’s how:

`import matplotlib.pyplot as plt`

Think of `plt`

as a shorthand that will save you some typing time later on.

**Your First Plot**

**Plot**: A graphical representation of data.

Let’s start with something simple, like plotting a line. Imagine you have the scores of 5 students in a test out of 10:

```
import matplotlib.pyplot as plt
scores = [7, 8, 6, 9, 8]
plt.plot(scores)
plt.show()
```

The `plt.plot()`

function draws the line, and `plt.show()`

displays it. When you run this, you’ll see a line connecting the scores of the students in the order they were listed.

**Function**: A block of organized, reusable code that performs a single, related action.

**Basic Plotting**

**Line Plots**

For a further instruction of line plotting, refer to:

What if you want to plot the scores against the names of the students? Easy peasy!

```
students = ["Anna", "Bob", "Charlie", "David", "Eva"]
scores = [55, 62, 89, 47, 65]
plt.plot(students, scores)
plt.show()
```

**Bar Charts**

For a further instruction about bar charts, refer to:

**Bar Chart**: A chart that represents data with rectangular bars.

Sometimes, a bar chart might be more appropriate to represent data. For instance, to compare the scores visually:

```
import matplotlib.pyplot as plt
students = ["Anna", "Bob", "Charlie", "David", "Eva"]
scores = [55, 62, 89, 47, 65]
plt.bar(students, scores, color='blue')
plt.show()
```

**Stacked Bar Charts**

For a further instruction about stacked bar charts, refer to:

**Stacked Bar Chart**: A bar chart that represents different groups on top of one another.

Visualize part-to-whole relationships and compare multiple categories.

```
import matplotlib.pyplot as plt
A = [5, 15, 7, 10]
B = [3, 7, 5, 8]
barWidth = 0.5
r = range(len(A))
plt.bar(r, A, width=barWidth, label='A', color='blue')
plt.bar(r, B, bottom=A, width=barWidth, label='B', color='red')
plt.legend()
plt.show()
```

**Pie Charts**

For a further instruction about pie charts, refer to:

**Pie Chart**: A circular chart divided into sectors, illustrating numerical proportion.

Want to represent parts of a whole? Pie charts are your go-to. Let’s say you want to represent the distribution of favorite fruits in a class:

```
import matplotlib.pyplot as plt
fruits = ["Apples", "Bananas", "Cherries", "Dates"]
count = [12, 15, 7, 5]
plt.pie(count, labels=fruits, autopct='%1.1f%%')
plt.show()
```

The `autopct`

parameter helps display the percentage on the pie chart.

**Customizing Your Plots**

**Titles and Labels**

For a further instruction about titles and labels, refer to:

A plot without labels is like a book without a title. Let’s add some:

```
import matplotlib.pyplot as plt
students = ["Anna", "Bob", "Charlie", "David", "Eva"]
scores = [55, 62, 89, 47, 65]
# Adding titles and labels
plt.plot(students, scores)
plt.title("Test Scores of Students")
plt.xlabel("Students")
plt.ylabel("Scores out of 10")
plt.show()
```

**Changing Line Styles and Colors**

For a further instruction about styles and colors, refer to:

You can change the style and color of your plots to make them more visually appealing or to represent different data sets distinctly:

```
import matplotlib.pyplot as plt
students = ["Anna", "Bob", "Charlie", "David", "Eva"]
scores = [55, 62, 89, 47, 65]
# Changing line styles and colors
plt.plot(students, scores, color='red', linestyle='--', marker='o')
plt.show()
```

**Legends**

If you have multiple lines or data sets in a single plot, legends can help differentiate them:

```
import matplotlib.pyplot as plt
students = ["Anna", "Bob", "Charlie", "David", "Eva"]
scores = [55, 62, 89, 47, 65]
scores2 = [6, 7, 8, 6, 7]
plt.plot(students, scores, label='Test 1')
plt.plot(students, scores2, label='Test 2')
plt.legend()
plt.show()
```

**Advanced Plotting Techniques**

**Histograms**

For a further instruction about histograms, refer to:

**Histogram**: A representation of the distribution of a dataset.

Want to see the distribution of data?

Histograms are perfect for that. Let’s say you have the scores of 30 students and want to see the distribution:

```
import matplotlib.pyplot as plt
# Sample Data
scores = [85, 87, 89, 90, 78, 85, 92, 72, 83, 88, 91, 85, 79, 80, 82, 85, 87, 88, 90, 91, 92, 93, 78, 80, 82, 85, 88, 90, 92, 95]
# Plotting. This may take a minute.
plt.hist(scores, bins=5, color='green', edgecolor='black')
plt.xlabel('Scores')
plt.ylabel('Number of Students')
plt.title('Distribution of Student Scores')
plt.show()
```

**Scatter Plots**

For a further instruction about scatter plots, refer to:

**Scatter Plot**: A type of data visualization that uses dots to represent the values obtained for two different variables.

Scatter plots are great for showing the relationship between two sets of data.

Imagine plotting the relationship between hours studied and test scores:

```
import matplotlib.pyplot as plt
# Sample Data
hours_studied = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
test_scores = [65, 70, 75, 80, 85, 90, 92, 93, 95, 97]
# Plotting
plt.scatter(hours_studied, test_scores, color='blue', marker='o')
plt.xlabel('Hours Studied')
plt.ylabel('Test Scores')
plt.title('Relationship between Hours Studied and Test Scores')
plt.show()
```

**Subplots**

For a further instruction about subplots, refer to:

**Subplot**: Multiple plots in a single figure.

Want to display multiple plots in a single figure? Subplots are here to help:

```
import matplotlib.pyplot as plt
students = ["Anna", "Bob", "Charlie", "David", "Eva"]
scores = [55, 62, 89, 47, 65]
scores2 = [6, 7, 8, 6, 7]
fig, axs = plt.subplots(2)
axs[0].plot(students, scores, label='Test 1')
axs[1].plot(students, scores2, label='Test 2', color='red')
plt.show()
```

**Enhancing Your Plots**

**Grids**

For a further instruction about grids, refer to:

Grids can make your plots easier to read:

```
import matplotlib.pyplot as plt
# Sample Data
students = ["Anna", "Bob", "Charlie", "David", "Eva"]
scores = [55, 62, 89, 47, 65]
# Plotting
plt.plot(students, scores)
plt.grid(True) # Adding the grids
plt.show()
```

**Text Annotations**

For a further instruction about text annotations, refer to:

Sometimes, you might want to highlight specific points in your plot:

```
import matplotlib.pyplot as plt
# Sample Data
students = ["Anna", "Bob", "Charlie", "David", "Eva"]
scores = [55, 62, 89, 47, 65]
# Plotting
plt.plot(students, scores)
plt.text(2, 88, 'Highest Score', fontsize=9, color='red')
plt.show()
```

**Saving Your Plots**

For a further instruction about saving plots, refer to:

After all the hard work, you might want to save your masterpiece:

```
import matplotlib.pyplot as plt
# Sample Data
students = ["Anna", "Bob", "Charlie", "David", "Eva"]
scores = [55, 62, 89, 47, 65]
# Plotting
plt.plot(students, scores)
plt.savefig('test_scores.png')
```

**3D Plotting**

For a comprehensive intruction about 3D plotting, refer to:

**3D Line Plot**

For a further instruction about 3D line plot, refer to:

Visualize data in three dimensions with a 3D line plot.

```
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Generating sample data. You may ignore this part.
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
xs = r * np.sin(theta)
ys = r * np.cos(theta)
zs = z
# Generating a 3D line plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(xs, ys, zs)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
```

**3D Scatter Plot**

For a further instruction about 3D scatter plots, refer to:

Display individual data points in 3D space.

```
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Generating sample data. You may ignore this part.
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
xs = r * np.sin(theta)
ys = r * np.cos(theta)
zs = z
# Plotting
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xs, ys, zs, c='r', marker='o')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
```

**Animations**

**Basic Animation**

For a further instruction about animations, refer to:

Bring your plots to life with simple animations.

```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'r-')
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128), init_func=init, blit=True)
plt.show()
```

**Additional Functionalities**

**Error Bars**

For a further instruction about error bars, refer to:

**Error Bars**: Graphical representation of data variability.

Display the variability of data and show error margins.

```
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
yerr = [0.5, 0.4, 0.3, 0.2]
plt.errorbar(x, y, yerr=yerr, fmt='o', color='blue', ecolor='red', capsize=5)
plt.show()
```