Mastering Treemaps and Carpet Plots in Python with Matplotlib

Data visualization is a crucial aspect of data science, allowing us to present complex datasets in an intuitive and meaningful way. Two powerful yet often underutilized visualization techniques are Treemaps and Carpet Plots. These methods help in displaying hierarchical and multi-dimensional data effectively. In this guide, we’ll explore how to master Treemaps and Carpet Plots using Python's Matplotlib and additional libraries.

1. Understanding Treemaps

A Treemap is a visualization that represents hierarchical data using nested rectangles. Each rectangle’s size and color correspond to numerical values, making it an effective tool for displaying proportions within a dataset.

Creating a Basic Treemap

We can create a simple treemap using Squarify, a Python library that facilitates the visualization of hierarchical data.

import matplotlib.pyplot as plt
import squarify

sizes = [30, 20, 50, 10]  # Example values
labels = ['A', 'B', 'C', 'D']
colors = ['red', 'green', 'blue', 'purple']

plt.figure(figsize=(8, 6))
squarify.plot(sizes=sizes, label=labels, color=colors, alpha=0.7)
plt.axis('off')
plt.title("Basic Treemap")
plt.show()

2. Adding Titles, Labels, and Customization

Customization helps make treemaps more informative and visually appealing. Adding labels, adjusting color intensity, and modifying text properties enhances readability.

plt.figure(figsize=(8, 6))
squarify.plot(sizes=sizes, label=labels, color=colors, alpha=0.6, edgecolor='white', linewidth=2)
plt.axis('off')
plt.title("Customized Treemap with Borders")
plt.show()

3. Advanced Treemap Customization with Color Maps

To make the treemap visually appealing and informative, we can use Matplotlib's color maps to assign colors dynamically based on values.

import numpy as np

sizes = [50, 30, 20, 10, 5]
labels = ['Parent', 'Child 1', 'Child 2', 'Grandchild 1', 'Grandchild 2']
colors = plt.cm.viridis(np.linspace(0, 1, len(sizes)))

plt.figure(figsize=(8, 6))
squarify.plot(sizes=sizes, label=labels, color=colors, alpha=0.7)
plt.axis('off')
plt.title("Hierarchical Treemap with Color Mapping")
plt.show()

4. Creating Animated Treemaps with Matplotlib

Animating treemaps can be useful when showing changes over time.

import matplotlib.animation as animation

def update(frame):
    plt.clf()
    dynamic_sizes = [frame * 2, 50 - frame, frame + 10, 20]
    squarify.plot(sizes=dynamic_sizes, label=labels, color=colors, alpha=0.7)
    plt.axis('off')
    plt.title(f"Animated Treemap - Frame {frame}")

fig = plt.figure(figsize=(8, 6))
ani = animation.FuncAnimation(fig, update, frames=10, interval=500)
plt.show()

5. Saving Treemap as Image and PDF

Once you've created a treemap, saving it as an image or PDF ensures easy sharing.

plt.figure(figsize=(8, 6))
squarify.plot(sizes=sizes, label=labels, color=colors, alpha=0.7)
plt.axis('off')
plt.title("Treemap for Saving")
plt.savefig("treemap.png", dpi=300)
plt.savefig("treemap.pdf")
plt.show()

6. Saving Treemap as GIF or Video

To save the animated treemap as a GIF or video file:

from matplotlib.animation import PillowWriter, FFMpegWriter

ani.save("treemap.gif", writer=PillowWriter(fps=5))  # Save as GIF
ani.save("treemap.mp4", writer=FFMpegWriter(fps=5))  # Save as Video

7. Understanding Carpet Plots

A Carpet Plot is a specialized 2D visualization that helps represent multidimensional data. It’s useful for showing relationships between two or more parameters over a continuous domain.

Creating a Basic Carpet Plot

We use Matplotlib and NumPy to construct a basic carpet plot.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

x = np.linspace(0, 10, 10)
y = np.sin(x)

points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

fig, ax = plt.subplots(figsize=(8, 5))
ax.set_title("Basic Carpet Plot")
line_segments = LineCollection(segments, cmap='viridis', linewidth=2)
ax.add_collection(line_segments)
ax.autoscale()
plt.show()

8. Saving Carpet Plot as Image and PDF

fig.savefig("carpetplot.png", dpi=300)
fig.savefig("carpetplot.pdf")

9. Creating GIF and Video Animations for Carpet Plots

ani = animation.FuncAnimation(fig, update, frames=10, interval=500)
ani.save("carpetplot.gif", writer=PillowWriter(fps=5))
ani.save("carpetplot.mp4", writer=FFMpegWriter(fps=5))

10. Summary

Mastering Treemaps and Carpet Plots in Python with Matplotlib expands your data visualization toolkit.

  • Treemaps effectively represent hierarchical data.

  • Carpet Plots offer a way to visualize multi-dimensional relationships.

  • Customizations such as labels, colors, and gridlines improve readability.

  • Animation can bring your visualizations to life.

  • Saving options ensure your plots are shareable in multiple formats.

By integrating these techniques, you can create insightful and professional-quality visualizations for various data analysis needs.