The most common way to plot a matrix is as a heatmap, where each cell gets a color representing its value. This works in Python, MATLAB, R, and most other data tools, typically in just a few lines of code. Depending on your data and goals, you might also use a 3D surface plot, a sparsity pattern plot, or an interactive visualization.
Heatmaps: The Default Choice
A heatmap maps every value in your matrix to a color on a gradient. Low values get one color, high values get another, and everything in between falls along the spectrum. This lets you see the entire dataset at once, spotting patterns, clusters, and outliers that would be invisible in a table of numbers.
Heatmaps work best when your matrix represents some measured quantity across two dimensions: time vs. sensors, genes vs. samples, rows vs. columns of any grid-structured data. The color gradient (or discrete color bins) is explained by a legend or color bar alongside the plot.
Plotting a Matrix in Python
Python offers three main approaches, each with different strengths.
Matplotlib’s imshow and matshow
The quickest option is built into Matplotlib. Both imshow and matshow render a 2D array as a color grid:
plt.imshow(matrix, cmap='viridis')displays the matrix as an image, mapping values to colors.plt.matshow(matrix)does essentially the same thing but places the x-axis labels on top, which feels more natural for matrix data.
Add plt.colorbar() after either call to show the value-to-color mapping. These functions accept any 2D NumPy array directly.
Seaborn’s Heatmap
Seaborn’s heatmap function gives you more control with less effort. It accepts a 2D NumPy array or a Pandas DataFrame. If you pass a DataFrame, it automatically uses the row and column labels as axis labels:
sns.heatmap(data, annot=True, fmt=".1f", cmap="viridis")
Setting annot=True prints each value directly inside its cell. The fmt parameter controls decimal places (“.1f” gives one decimal place, “.2g” is the default for compact formatting). You can also draw grid lines between cells with linewidths, force square cells with square=True, or mask certain values to hide them from the plot.
Plotly for Interactive Plots
If you need to zoom, hover over cells to read exact values, or embed the plot in a web page, Plotly is the better tool. Its heatmap function creates an interactive version where hovering over any cell shows its row, column, and value. You can display text directly on cells with text_auto=True, and control the number format with a d3-format string. For matrices with missing data, setting hoverongaps=False prevents tooltips from appearing on empty cells.
Plotting a Matrix in MATLAB
MATLAB has strong built-in support for matrix visualization. The imagesc function is the most common starting point. It scales matrix values to the full range of the current colormap and displays the result as a colored grid. Follow it with colorbar to add the legend.
For 3D visualization, surf treats each matrix element as a height value on a surface. You’ll need X and Y coordinate vectors (or matrices created with meshgrid) plus a Z matrix of values. Only Z needs to be a matrix; X and Y can be simple vectors. The call looks like surf(X, Y, Z, 'EdgeColor', 'none'), where turning off edge color produces a smooth surface rather than a wireframe.
Plotting a Matrix in R
In R, the ggplot2 package handles matrix heatmaps through geom_tile. You first reshape your matrix into a long-format data frame with columns for row, column, and value (the reshape2::melt or tidyr::pivot_longer functions handle this). Then map row to the y-axis, column to the x-axis, and value to fill color. The base R image function also works for quick plots without any reshaping.
Choosing the Right Color Map
Your choice of color map can make or break the visualization. The old defaults in many tools, often called “jet” or “rainbow,” distort how you perceive the data. They create artificial bright bands and dark zones that don’t correspond to actual patterns in the matrix. A 2020 study in Nature Communications documented how these unscientific color maps make it significantly harder to infer the true structure of a dataset.
Perceptually uniform color maps solve this problem. The most widely used ones are viridis, magma, plasma, and inferno, all developed for Matplotlib but now available in most plotting libraries. “Perceptually uniform” means that equal steps in data value produce equal steps in perceived color change. A value difference of 10 looks the same whether you’re in the low range or the high range of the scale. Use cmap='viridis' (or any of the others) as your default, and switch to a diverging color map only when your data has a meaningful center point, like zero in a correlation matrix.
3D Surface Plots
When your matrix represents a function of two variables, a 3D surface plot can reveal the shape of that function more intuitively than a flat heatmap. Each cell’s row index maps to X, its column index maps to Y, and its value becomes the Z height.
In Python, you create this with Matplotlib’s plot_surface method. First generate coordinate grids with np.meshgrid, then call ax.plot_surface(X, Y, Z, cmap='viridis') on a 3D axes object. In MATLAB, the equivalent is the surf function described above. Surface plots are particularly useful for optimization landscapes, terrain data, or any matrix where the “height” of values carries physical meaning.
Visualizing Sparse Matrices
If your matrix is mostly zeros, a heatmap is a poor choice because it’ll be almost entirely one color. Instead, use a sparsity pattern plot that simply marks where the nonzero values are. MATLAB’s spy function does exactly this: it colors nonzero entries and leaves zero entries white, giving you an instant picture of the matrix’s structure. In Python, matplotlib.pyplot.spy provides the same functionality.
Sparsity plots are common in linear algebra, network analysis, and any domain where you care more about which entries exist than what their exact values are. One practical note: the aspect ratio of spy plots has a 1-to-10 limit, after which the plot stops adjusting to match the matrix shape. For very rectangular matrices, you may need to adjust figure dimensions manually.
Preprocessing Before Plotting
When your matrix columns represent different quantities on wildly different scales (say, one column ranges from 0 to 1 and another from 0 to 10,000), the high-magnitude column will dominate the color map and flatten everything else into a single shade. Two common fixes address this.
Min-max scaling compresses each column (or the whole matrix) to a 0-to-1 range using the formula: scaled = (value – min) / (max – min). This works well when your data is roughly uniformly distributed without extreme outliers. Z-score scaling instead converts each value to how many standard deviations it sits from the mean: scaled = (value – mean) / standard deviation. This is the better choice when the data follows something close to a normal distribution. If outliers are a problem even after Z-score scaling, you can clip extreme values before plotting.
Keep in mind that normalization changes the values displayed. Always label your color bar to indicate whether you’re showing raw values, min-max scaled values, or Z-scores, so the plot doesn’t mislead.

