WikiGalaxy

Personalize

Matplotlib: Heatmaps and Contour Plots

Introduction to Heatmaps

What is a Heatmap?

A heatmap is a graphical representation of data where individual values are represented as colors. It is particularly useful for visualizing the magnitude of values across a two-dimensional space, making it easier to identify patterns, correlations, and anomalies.

Applications of Heatmaps

Heatmaps are widely used in various fields such as biology, finance, and data science for tasks like displaying gene expression data, financial market data, and more.


import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(10, 10)
plt.imshow(data, cmap='hot', interpolation='nearest')
plt.colorbar()
plt.title('Random Heatmap')
plt.show()
    

Explanation of Code

In this example, we use numpy to generate a 10x10 matrix of random numbers. The imshow function from Matplotlib is used to create the heatmap, with the 'hot' colormap applied. The colorbar function adds a color scale to the side of the heatmap.

Contour Plots

What is a Contour Plot?

A contour plot is a graphical technique for representing a 3D surface by plotting constant z slices, called contours, on a 2D format. This type of plot is useful for visualizing the levels of a variable over a plane.

Applications of Contour Plots

Contour plots are commonly used in meteorology for weather maps, in engineering for stress analysis, and in physics for potential fields.


import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3.0, 3.0, 100)
y = np.linspace(-3.0, 3.0, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X**2 + Y**2)

plt.contour(X, Y, Z)
plt.title('Contour Plot of sin(x² + y²)')
plt.show()
    

Explanation of Code

This example generates a contour plot for the function sin(x² + y²). We use numpy.meshgrid to create a grid of x and y values, and the contour function from Matplotlib to plot the contours.

Annotated Heatmaps

Why Annotate Heatmaps?

Annotations in heatmaps provide additional information about the values in each cell, making it easier to interpret the data. This is particularly useful when presenting data to an audience that may not be familiar with the dataset.


import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(5, 5)
fig, ax = plt.subplots()
cax = ax.matshow(data, cmap='viridis')

for (i, j), val in np.ndenumerate(data):
    ax.text(j, i, f'{val:.2f}', ha='center', va='center', color='white')

plt.colorbar(cax)
plt.title('Annotated Heatmap')
plt.show()
    

Explanation of Code

In this annotated heatmap, we use np.ndenumerate to iterate over each element in the data matrix. The text function is used to add annotations to each cell, displaying the value with two decimal places.

Filled Contour Plots

What is a Filled Contour Plot?

Filled contour plots are similar to contour plots but with the areas between the lines filled with colors. This provides a clearer visualization of the different levels in the data.


import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3.0, 3.0, 100)
y = np.linspace(-3.0, 3.0, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X**2 + Y**2)

plt.contourf(X, Y, Z, cmap='plasma')
plt.colorbar()
plt.title('Filled Contour Plot of sin(x² + y²)')
plt.show()
    

Explanation of Code

This example uses the contourf function to create a filled contour plot. The 'plasma' colormap is applied to fill the areas between the contour lines, enhancing the visual representation of data levels.

Customizing Heatmaps

Why Customize Heatmaps?

Customizing heatmaps allows you to tailor the visualization to better suit your data and audience. This can include changing colormaps, adjusting aspect ratios, or adding labels and titles.


import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(7, 7)
fig, ax = plt.subplots(figsize=(8, 8))
cax = ax.matshow(data, cmap='coolwarm', aspect='auto')

plt.colorbar(cax)
plt.title('Customized Heatmap')
plt.xlabel('X Axis Label')
plt.ylabel('Y Axis Label')
plt.show()
    

Explanation of Code

In this example, we customize the heatmap by setting the figure size and using the 'coolwarm' colormap. The aspect='auto' parameter adjusts the aspect ratio, and labels are added to the axes for clarity.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025