PART 2 — Intermediate Concepts & Layouts

Python tutorial · PySpark.in

This part covers plotting layouts, styling, axes control, and customization options.

  1. Subplots (Using plt.subplot())

Allows displaying multiple plots in a single figure by dividing the screen into rows and columns. Each subplot is selected using (rows, columns, index).

```

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,5])

plt.subplot(2, 2, 3)

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

plt.subplot(2, 2, 4)

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

plt.show()

```

Subplots (Using fig, ax = plt.subplots())

A more flexible and professional method for creating multiple plots. Each axis (ax[i]) works like an individual canvas for custom plotting.

```

import matplotlib.pyplot as plt

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

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

ax[1].bar(['A','B','C'], [5,3,4])

plt.tight_layout()

plt.show()

```

Styles & Themes

Matplotlib provides pre-designed themes to quickly enhance the look of plots.
Example: 'ggplot', 'seaborn', 'dark_background'.

```

import matplotlib.pyplot as plt

plt.style.use('ggplot')

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

plt.show()

```

Axis Limits

xlim() and ylim() allow manual control of the visible range of the X-axis and Y-axis. Helps zoom into specific data regions.

```

import matplotlib.pyplot as plt

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

plt.xlim(0, 5)

plt.ylim(0, 6)

plt.show()

```

Ticks & Tick Rotation

xticks() and yticks() customize tick values and labels. Rotation improves readability of long labels.

```

import matplotlib.pyplot as plt

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

plt.xticks([1,2,3], ['Start', 'Middle', 'End'], rotation=45)

plt.yticks([3,4,5])

plt.show()

```

Text & Annotations

Adds descriptive comments or arrows on specific points of the graph to highlight important features.

```

import matplotlib.pyplot as plt

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

plt.annotate("Peak", xy=(2,5), xytext=(1,6),arrowprops=dict(facecolor='black'))


plt.show()

```

Alpha (Transparency)

alpha parameter controls plot transparency (0 = invisible, 1 = opaque). Useful when overlapping multiple shapes or points.

```

import matplotlib.pyplot as plt

plt.scatter([1,2,3],[4,5,6], alpha=0.5)

plt.show()

```

Line Width

linewidth sets the thickness of plotted lines, improving clarity and emphasis.

```

import matplotlib.pyplot as plt

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

plt.show()

```

Customizing Axes

Axes elements (spines, ticks) can be hidden or styled. Common use: remove top/right borders for a cleaner, modern look.

```

import matplotlib.pyplot as plt

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

ax = plt.gca()

ax.spines['top'].set_visible(False)

ax.spines['right'].set_visible(False)

plt.show()

```

Step Plot

Creates plots where values change in steps instead of smooth lines. Commonly used in digital signals, inventory, and stock market data.

```

import matplotlib.pyplot as plt

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

plt.show()

```

Stacked Bar Chart

Visualizes contribution of different groups on top of each other. Shows how parts make up a whole over categories.

```

import matplotlib.pyplot as plt

x = [1,2,3]

a = [3,4,2]

b = [2,3,1]

plt.bar(x, a)

plt.bar(x, b, bottom=a)

plt.show()

```

Fill Between

Shades the area between two curves or between a curve and baseline. Used for confidence bands and ranges.

```

import matplotlib.pyplot as plt

x = [1,2,3]

y1 = [2,3,4]

y2 = [1,2,2]

plt.fill_between(x, y1, y2, color='lightblue')

plt.show()

```

Twin Axes

Creates a second Y-axis on the right side for displaying different scale values on the same plot. Useful when comparing units like temperature vs rainfall.

```

import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()

ax1.plot([1,2,3],[2,3,4], color='blue')

ax2.plot([1,2,3],[50,60,70], color='red')

plt.show()

```

Axis Inversion

invert_xaxis() and invert_yaxis() reverse display direction of axes. Used for ranking charts, reverse timelines, special scientific plots.

```

import matplotlib.pyplot as plt

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

plt.gca().invert_xaxis()

plt.gca().invert_yaxis()

plt.show()

```

Removing Axis

plt.axis('off') hides both axes and borders. Ideal for shapes, patterns, and image-based visualizations.

```

import matplotlib.pyplot as plt

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

plt.axis('off')

plt.show()

```

Heatmap and Colorbar

imshow() displays 2D numeric data as colors, forming a heatmap. colorbar() provides a scale reference for color intensity.

```

import matplotlib.pyplot as plt

import numpy as np

data = np.random.rand(5,5)

plt.imshow(data, cmap='viridis')

plt.colorbar()

plt.show()

```

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges