Part 1-Matplotlib Basics & Essential Plots

Python tutorial · PySpark.in

Matplotlib

Matplotlib is a powerful Python library used for data visualization. It allows you to create a wide variety of graphs, charts, and plots to understand data better.It is the most commonly used plotting library in Python and is often used in:

Why is Matplotlib Used?

1. Visualizes Data Easily

It helps convert raw data into visual form like:

Visualization makes data easier to understand.

2. Helps in Data Analysis

Graphs reveal patterns, trends, and relationships that numbers alone cannot show.

3. Highly Customizable

You can customize everything:

4. Supports Many Types of Plots

Matplotlib provides simple to advanced plots including:

5. Works Well With NumPy, Pandas & SciPy

Most data science workflows use Matplotlib along with:

6. Used for Reports & Dashboards

You can save plots as:

Useful for:

1. Importing Matplotlib

```

import matplotlib.pyplot as plt

```

2. Basic Plot (Line Plot)

A line plot is the simplest visualization used to show trends or changes over time by connecting data points with straight lines.

```

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,4,1])

plt.show()

```

3. Plot with Label, Title, Axis Labels

You can enhance a plot by adding:

```

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,4,1])

plt.title("Simple Plot")

plt.xlabel("X Axis")

plt.ylabel("Y Axis")

plt.show()

```

4. Markers, Colors, Line Styles

Used to customize line appearance.

```

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,4,1], marker='o', linestyle='--', color='red')

plt.show()

```

Common markers: o, *, s, D, x, +
Line styles: -, --, -. , :
Colors: 'r','g','b','k','c','m','y'

5. Multiple Plots in Same Graph

Allows plotting more than one line in the same figure for comparison.
plt.legend() displays labels of each line.

```

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,4,1], label='Line A')

plt.plot([1,2,3], [1,3,2], label='Line B')

plt.legend()

plt.show()

```

6. Bar Chart

Represents categorical data using rectangular bars.

Vertical

```

import matplotlib.pyplot as plt

plt.bar(['A','B','C'], [10,20,15])

plt.show()

```

Horizontal

```

import matplotlib.pyplot as plt

plt.barh(['A','B','C'], [10,20,15])

plt.show()

```

7. Scatter Plot

Displays the relationship between two numeric variables using points. Best used for correlation analysis.

```

import matplotlib.pyplot as plt

plt.scatter([1,2,3,4], [3,4,2,5])

plt.show()

```

8. Histogram

Shows the distribution of continuous data by grouping values into bins (intervals). Helps understand frequency patterns.

```

import matplotlib.pyplot as plt

import numpy as np

data = np.random.randn(600)

plt.hist(data, bins=20)

plt.show()

```

9. Pie Chart

Represents percentage distribution of categories as slices of a circle.
autopct parameter shows the percentage value.

```

import matplotlib.pyplot as plt

plt.pie([40,30,20,10], labels=['A','B','C','D'], autopct='%1.1f%%')

plt.show()

```

10. Boxplot

Shows data spread and outliers using minimum, Q1, median, Q3, and maximum values. Useful for statistical analysis.

```

import matplotlib.pyplot as plt

plt.boxplot([10,20,15,25,30])

plt.show()

```

11. Area Plot

Shades the area under the line — used to show cumulative trends or magnitude.

```

import matplotlib.pyplot as plt

x = [1,2,3,4]

y = [2,4,1,5]

plt.fill_between(x, y)

plt.show()

```

12. Subplots (Multiple Graphs Layout)

Used to display multiple charts in one window.

Option 1: plt.subplot()

```

import matplotlib.pyplot as plt

plt.subplot(2,2,1)

plt.plot([1,2,3])

plt.subplot(2,2,2)

plt.bar([1,2,3], [3,4,2])

plt.subplot(2,2,3)

plt.scatter([1,2,3], [3,2,1])

plt.subplot(2,2,4)

plt.hist(np.random.randn(100))

plt.show()

```

Option 2: fig, ax = plt.subplots()

```

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2,2)

ax[0,0].plot([1,2,3],[2,1,3])

ax[0,1].bar(['A','B'], [10,20])

ax[1,0].scatter([1,2], [4,5])

ax[1,1].hist(np.random.randn(100))

plt.tight_layout()

plt.show()

```

13. Grid

Adds horizontal/vertical reference lines to the plot for better readability.

```

import matplotlib.pyplot as plt

plt.plot([1,2,3], [1,4,9])

plt.grid(True)

plt.show()

```

14. Figure Size

Controls the width and height of the plot window using figsize=(w,h).

```

import matplotlib.pyplot as plt

plt.figure(figsize=(8,4))

plt.plot([1,2,3])

plt.show()

```

15. Axis Limits

Manually set the visible range of X and Y axes using xlim() and ylim().

```

import matplotlib.pyplot as plt

plt.plot([1,2,3],[2,5,1])

plt.xlim(0,5)

plt.ylim(0,10)

plt.show()

```

16. Annotations (Add text on graph)

Adds comment with arrow to highlight a specific point on the graph.

```

import matplotlib.pyplot as plt

plt.plot([1,2,3,4], [10,20,25,22])

plt.annotate("Peak", xy=(3,25), xytext=(2,27), arrowprops=dict(facecolor='black'))

plt.show()

```

17. Legends

Displays labels of plotted graphs. loc parameter controls legend position.

```

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,4,1], label="Sales")

plt.legend(loc='upper left')

plt.show()

```

18. Add Text on Plot

plt.text() prints custom text directly on the plot (non-arrow label).

```

import matplotlib.pyplot as plt

plt.text(2,4,"Important Point")

plt.plot([1,2,3],[2,4,1])

plt.show()

```

19. Change Style (Themes)

Matplotlib provides pre-defined design themes like 'ggplot', 'seaborn', 'dark_background' to improve the look of charts.

```

import matplotlib.pyplot as plt

plt.plot([1,2,3],[2,4,1])

plt.style.use('ggplot')

plt.show()

```

Available styles:

```

import matplotlib.pyplot as plt

import matplotlib.pyplot as plt

print(plt.style.available)

```

20. Saving Figures

plt.savefig() saves the plot in formats such as PNG, PDF, JPG, SVG, etc.

```

import matplotlib.pyplot as plt

plt.plot([1,2,3])

plt.savefig("plot.png") # PNG

plt.savefig("plot.pdf") # PDF

```

21. Adjust Spacing

plt.tight_layout() fixes overlapping of titles, labels, and subplots.

```

import matplotlib.pyplot as plt

plt.plot([1,2,3])

plt.tight_layout()

```

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges