Create heatmap chart - MATLAB heatmap (2024)

Table of Contents
Syntax Description Table Data Matrix Data Additional Options Examples Create Heatmap from Tabular Data Reorder Heatmap Labels Specify Table Variable for Heatmap Colors Specify Calculation Method for Color Data Create Heatmap from Matrix Data Create Heatmap from Matrix Data Using Custom Axis Labels Use LaTeX for Greek Letters in Title Normalize Colors Along Each Row or Column Compute Color Data Using Custom Aggregation Method Compare Heatmaps with Different Numbers of Colors Input Arguments tbl — Source table table | timetable xvar — Table variable for x-axis character vector | string scalar | numeric scalar | logical vector yvar — Table variable for y-axis character vector | string scalar | numeric scalar | logical vector cvar — Table variable for color data character vector | string scalar | numeric scalar | logical vector cdata — Color data matrix xvalues — Values appearing along x-axis categorical array | string array | numeric array | cell array of character vectors yvalues — Values appearing along y-axis categorical array | string array | numeric array | cell array of character vectors parent — Parent container Figure object | Panel object | Tab object | TiledChartLayout object | GridLayout object Name-Value Arguments Output Arguments h — Heatmap chart object HeatmapChart object More About Standalone Visualization Tips Version History R2019a: Heatmaps interpret text using TeX markup See Also Functions Properties Topics MATLAB Command Americas Europe Asia Pacific FAQs References

Create heatmap chart

collapse all in page

  • Create heatmap chart - MATLAB heatmap (1)

Syntax

heatmap(tbl,xvar,yvar)

heatmap(tbl,xvar,yvar,'ColorVariable',cvar)

heatmap(cdata)

heatmap(xvalues,yvalues,cdata)

heatmap(___,Name,Value)

heatmap(parent,___)

h = heatmap(___)

Description

Table Data

example

heatmap(tbl,xvar,yvar) creates a heatmap by aggregating the variables in the table tbl. Specify xvar and yvar as the table variables that you want to visualize. The numbers in the cells and the default colors correspond to the number of times each (x, y) pair appears together in the table. The resulting x-axis and y-axis show unique values from the xvar and yvar variables respectively.

example

heatmap(tbl,xvar,yvar,'ColorVariable',cvar) uses the table variable specified by cvar to calculate the numbers in the cells and the corresponding colors. The default calculation method is a mean aggregation, so the cell numbers and colors are based on the average value of cvar for each (x, y) pair that appears together in the table.

Matrix Data

example

heatmap(cdata) creates a heatmap from the 2-D matrix cdata, which contains pre-aggregated data. The heatmap has one cell for each value in cdata.

example

heatmap(xvalues,yvalues,cdata) specifies the labels for the values that appear along the x-axis and y-axis.

Additional Options

example

heatmap(___,Name,Value) specifies additional options for the heatmap using one or more name-value pair arguments. Specify the options after all other input arguments. For a list of properties, see HeatmapChart Properties.

heatmap(parent,___) creates the heatmap in the figure, panel, or tab specified by parent.

h = heatmap(___) returns the HeatmapChart object. Use h to modify properties of the chart after creating it. For a list of properties, see HeatmapChart Properties.

Examples

collapse all

Create Heatmap from Tabular Data

Open Live Script

Create a heatmap from a table of data for medical patients.

Load the patients data set and create a table from a subset of the variables loaded into the workspace. Then create a heatmap that counts the total number of patients with the same set of Smoker and SelfAssessedHealthStatus values.

load patientstbl = table(LastName,Age,Gender,SelfAssessedHealthStatus,... Smoker,Weight,Location);h = heatmap(tbl,'Smoker','SelfAssessedHealthStatus');

Create heatmap chart - MATLAB heatmap (2)

Reorder Heatmap Labels

Open Live Script

Create a heatmap and reorder the labels along the y-axis.

Load the patients data set and create a heatmap from the data. Assign the HeatmapChart object to the variable h.

load patientstbl = table(LastName,Age,Gender,SelfAssessedHealthStatus,... Smoker,Weight,Location);h = heatmap(tbl,'Smoker','SelfAssessedHealthStatus');

Create heatmap chart - MATLAB heatmap (3)

Reorder the labels along the y-axis.

h.YDisplayData = {'Excellent','Good','Fair','Poor'};

Create heatmap chart - MATLAB heatmap (4)

Alternatively, you can reorder the labels by changing the data to categorical data and then reordering the categories using the reordercats function. Similarly, you can add, remove, or rename the heatmap labels using the addcats, removecats, or renamecats functions, respectively.

Specify Table Variable for Heatmap Colors

Open Live Script

Create a heatmap and specify the table variable to use when determining the heatmap cell colors.

Load the patients data set and create a heatmap from the data. Color each cell using the average age of patients with a particular pair of Smoker and SelfAssessedHealthStatus values by setting the ColorVariable option to 'Age'.

load patientstbl = table(LastName,Age,Gender,SelfAssessedHealthStatus,... Smoker,Weight,Location);h = heatmap(tbl,'Smoker','SelfAssessedHealthStatus',... 'ColorVariable','Age');

Create heatmap chart - MATLAB heatmap (5)

Specify Calculation Method for Color Data

Open Live Script

Create a heatmap and specify the table variable and calculation method to use when determining the heatmap cell colors.

Load the patients data set and create a heatmap from the data. Color each cell using the median age of patients with a particular pair of Smoker and SelfAssessedHealthStatus values. Specify the ColorVariable option as 'Age' and the ColorMethod option as 'median'.

load patientstbl = table(LastName,Age,Gender,SelfAssessedHealthStatus,... Smoker,Weight,Location);h = heatmap(tbl,'Smoker','SelfAssessedHealthStatus',... 'ColorVariable','Age','ColorMethod','median');

Create heatmap chart - MATLAB heatmap (6)

Create Heatmap from Matrix Data

Open Live Script

Create a matrix of data. Then create a heatmap of the matrix values. The default labels along the x-axis and y-axis appear as 1, 2, 3, and so on.

cdata = [45 60 32; 43 54 76; 32 94 68; 23 95 58];h = heatmap(cdata);

Create heatmap chart - MATLAB heatmap (7)

Create Heatmap from Matrix Data Using Custom Axis Labels

Open Live Script

Create a matrix of data. Then create a heatmap of the matrix values. Use custom labels along the x-axis and y-axis by specifying the first two input arguments as the labels you want. Specify the title and axis labels by setting properties of the HeatmapChart object.

cdata = [45 60 32; 43 54 76; 32 94 68; 23 95 58];xvalues = {'Small','Medium','Large'};yvalues = {'Green','Red','Blue','Gray'};h = heatmap(xvalues,yvalues,cdata);h.Title = 'T-Shirt Orders';h.XLabel = 'Sizes';h.YLabel = 'Colors';

Create heatmap chart - MATLAB heatmap (8)

Use LaTeX for Greek Letters in Title

Since R2023b

Open Live Script

To use LaTeX (or TeX) markup in the title, axis labels, or data tips, set the Interpreter property of the HeatmapChart object.

For example, create a heatmap chart with a title that uses LaTeX to display Greek letters. Set the Interpreter property to "latex" when you create the chart. Then include the markup when you call the title function.

heatmap(randi(100,5,3),Interpreter="latex")title("$\hat{\psi_1}$ Values for ${1\le\alpha\le3}$")

Create heatmap chart - MATLAB heatmap (9)

Normalize Colors Along Each Row or Column

Open Live Script

Create a heatmap and normalize the colors along each column or row by setting the ColorScaling property.

Read the sample file outages.csv into a table. The sample file contains data representing electric utility outages in the Unites States. The table contains six columns: Region, OutageTime, Loss, Customers, RestorationTime, and Cause. Display the first five rows of each column.

T = readtable('outages.csv');T(1:5,:)
ans=5×6 table Region OutageTime Loss Customers RestorationTime Cause _____________ ________________ ______ __________ ________________ ___________________ {'SouthWest'} 2002-02-01 12:18 458.98 1.8202e+06 2002-02-07 16:50 {'winter storm' } {'SouthEast'} 2003-01-23 00:49 530.14 2.1204e+05 NaT {'winter storm' } {'SouthEast'} 2003-02-07 21:15 289.4 1.4294e+05 2003-02-17 08:14 {'winter storm' } {'West' } 2004-04-06 05:44 434.81 3.4037e+05 2004-04-06 06:10 {'equipment fault'} {'MidWest' } 2002-03-16 06:18 186.44 2.1275e+05 2002-03-18 23:23 {'severe storm' }

Create a heatmap that shows the different regions along the x-axis and the different outage causes along the y-axis. In each cell, show how many times each region experienced a power outage due to a particular cause.

h = heatmap(T,'Region','Cause');

Create heatmap chart - MATLAB heatmap (10)

Normalize the colors along each column. The smallest value in each column maps to the first color in the colormap and the largest value maps to the last color. The last color indicates the cause that caused the most power outages for each region.

h.ColorScaling = 'scaledcolumns';

Create heatmap chart - MATLAB heatmap (11)

Normalize the colors along each row instead. The smallest value in each row maps to the first color in the colormap and the largest value maps to the last color. The last color indicates the region that experienced the most power outages due to each cause.

h.ColorScaling = 'scaledrows';

Create heatmap chart - MATLAB heatmap (12)

Compute Color Data Using Custom Aggregation Method

Open Live Script

Create a heatmap and color the cells using data computed with a custom aggregation method. Use the pivot function to compute the color data.

Read the sample file TemperatureData.csv into a table. The file contains four columns: Year, Month, Day, and TemperatureF.

tbl = readtable('TemperatureData.csv');

Compute the color data as the maximum temperature for each month and year combination using the pivot function. Use NaN for missing month and year combinations.

P = pivot(tbl,Columns="Month",Rows="Year",DataVariable="TemperatureF",Method=@(x) mean(x,"includenan"))
P=2×13 table Year April August December February January July June March May November October September ____ ______ ______ ________ ________ _______ ______ ______ ______ ______ ________ _______ _________ 2015 43.267 69.903 40.548 15.448 21.355 69.161 59.967 28.484 57.548 43.8 49.323 64.467 2016 42.267 NaN NaN 29.966 27.71 68.824 63.733 37.806 53.806 NaN NaN NaN 

Rearrange the variables in the pivoted table.

P = P(:,["Year" "January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December"]);

Create the heatmap, and color the heatmap cells using the computed data values.

xvar = P.Properties.VariableNames(2:end);yvar = string(P.(1));cvar = P{:,2:end};heatmap(xvar,yvar,cvar)title("Maximum Temperatures (F)")

Create heatmap chart - MATLAB heatmap (13)

Compare Heatmaps with Different Numbers of Colors

Open Live Script

Heatmap charts use the 256-sampling of the sky colormap by default. You can change the sampling by specifying the Colormap name-value argument.

For example, create two heatmap charts in a 2-by-1 tiled chart layout. The top chart uses the default set of 256 colors, and the bottom chart uses only two colors.

tiledlayout(2,1,TileSpacing="compact")% Top chart with default colorsnexttileheatmap(magic(10))% Bottom chart with two colorsnexttileheatmap(magic(10),Colormap=sky(2))

Create heatmap chart - MATLAB heatmap (14)

Input Arguments

collapse all

tblSource table
table | timetable

Source table, specified as a table or timetable.

You can create a table from workspace variables using the table function, or you can import data as a table using the readtable function. You can create a timetable from workspace variables using the timetable function.

The SourceTable property of the HeatmapChart object stores the source table.

xvarTable variable for x-axis
character vector | string scalar | numeric scalar | logical vector

Table variable for x-axis, specified in oneof these forms:

  • Character vector or string scalar indicating one of the variable names. For example, heatmap(tbl,'HealthStatus','Gender') selects the variable named 'HealthStatus' for the x-axis.

  • Numeric scalar indicating the table variable index.For example, heatmap(tbl,2,3) selects the secondvariable in the table for the x-axis.

  • Logical vector containing one true element.

The values associated with your table variable must be groupedinto a finite set of discrete categories that the categorical function accepts. If thevalues are not grouped into a finite set of categories, use the discretize function to group them.

The labels that appear along the x-axisare in alphabetical order. You can customize the labels using categoricalarrays. For an example, see Create Heatmap from Tabular Data.

The XVariable property of the HeatmapChart objectstores the selected variable.

yvarTable variable for y-axis
character vector | string scalar | numeric scalar | logical vector

Table variable for y-axis, specified in oneof these forms:

  • Character vector or string scalar of one of the variable names. For example, heatmap(tbl,'HealthStatus','Gender') selects the variable named 'Gender' for the y-axis.

  • Numeric scalar indicating the table variable index.For example, heatmap(tbl,2,3) selects the thirdvariable in the table for the y-axis.

  • Logical vector containing one true element.

The values associated with your table variable must be groupedinto a finite set of discrete categories that the categorical function accepts. If thevalues are not grouped into a finite set of categories, use the discretize function to group them.

The labels that appear along the y-axisare in alphabetical order. You can customize the labels using categoricalarrays. For an example, see Create Heatmap from Tabular Data.

The YVariable property of the HeatmapChart objectstores the selected variable.

cvarTable variable for color data
character vector | string scalar | numeric scalar | logical vector

Table variable for color data, specified in one of these forms:

  • A character vector or string scalar of one of the variable names. For example, heatmap(__,'ColorVariable','HealthStatus') selects the variable named 'HealthStatus' for the y-axis.

  • A numeric scalar indicating the table variable index.For example, heatmap(__,'ColorVariable',1) selectsthe third variable in the table for the y-axis.

  • A logical vector containing one true element.

The values associated with your table variable must be of anumeric type or logical.

The property value is empty [] when using matrix data. The ColorVariable property of the HeatmapChart object stores the selected variable. The ColorData property populates with data based on the selected variable.

By default, heatmap calculates the colordata based on a mean aggregation. To change the calculation method,set the ColorMethod property.

cdataColor data
matrix

Color data for the heatmap cells, specified as a matrix.

The ColorData property of the HeatmapChart object stores the values.

Example: [40 24 68; 68 37 58; 49 23 46]

xvaluesValues appearing along x-axis
categorical array | string array | numeric array | cell array of character vectors

Values appearing along the x-axis, specifiedas a categorical array, string array, numeric array, or cell arrayof character vectors.

Example: {'small','medium','large'}

Example: categorical({'small','medium','large'})

yvaluesValues appearing along y-axis
categorical array | string array | numeric array | cell array of character vectors

Values appearing along y-axis, specifiedas a categorical array, string array, numeric array, or cell arrayof character vectors.

Example: {'small','medium','large'}

Example: categorical({'small','medium','large'})

parentParent container
Figure object | Panel object | Tab object | TiledChartLayout object | GridLayout object

Parent container, specified as a Figure, Panel, Tab, TiledChartLayout, or GridLayout object.

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: heatmap(tbl,xvar,yvar,'ColorVariable','Temperatures','ColorMethod','median')

Note

The properties listed here are only a subset. For a completelist, see HeatmapChart Properties.

Output Arguments

collapse all

h — Heatmap chart object
HeatmapChart object

HeatmapChart object, which is a standalone visualization. Use h to set properties on the heatmap chart after creating it.

More About

collapse all

Standalone Visualization

A standalone visualization is a chart designed for a special purpose that works independently from other charts. Unlike other charts such as plot and surf, a standalone visualization has a preconfigured axes object built into it, and some customizations are not available. A standalone visualization also has these characteristics:

  • It cannot be combined with other graphics elements, such as lines, patches, or surfaces. Thus, the hold command is not supported.

  • The gca function can return the chart object as the current axes.

  • You can pass the chart object to many MATLAB functions that accept an axes object as an input argument. For example, you can pass the chart object to the title function.

Tips

  • To interactively explore the data in your heatmap, use these options.

    • Zoom — Use the scroll wheel or the + and - keys to zoom.

    • Pan — Click and drag the heatmap or use the arrow keys to pan across the rows or columns.

    • Data tips — Hover over the heatmap to display a data tip.

    • Rearrange rows and columns — Click and drag a row or column label to move it to a different position.

    • Sort values — Click the icon that appears when you hover over the row or column label. Click once to sort the values in ascending order, twice to sort the values in descending order, and a third time to reset the order.

  • If you create a heatmap chart from a table, then you can customize its data tips.

    • To add or remove a row from the data tip, right-click anywhere on the chart and point to Modify Data Tips. Then, select or deselect a variable.

    • To add or remove multiple rows, right-click on the chart, point to Modify Data Tips, and select More. Then, add variables by clicking >> or remove them by clicking <<.

Version History

Introduced in R2017a

expand all

Starting in R2019a, heatmaps interpret text using TeX markup instead of displaying the literal characters. If you want to use a TeX markup character in regular text, such as an underscore (_), then insert a backslash (\) before the character you want to include. The backslash is the TeX escape character. For more information on using TeX markup, see the Interpreter property of the text object.

See Also

Functions

  • sorty | sortx | pivot | table | readtable | categorical | sky

Properties

  • HeatmapChart Properties

Topics

  • Create Heatmap from Tabular Data
  • Access Data in Tables

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

 

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Create heatmap chart - MATLAB heatmap (15)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

Contact your local office

Create heatmap chart - MATLAB heatmap (2024)

FAQs

How to create a heatmap in Matlab? ›

Create Basic Heatmap

Assign the HeatmapChart object to the variable h . Use h to modify the chart after it is created. h = heatmap(tbl,'Month','Year','ColorVariable','TemperatureF'); By default, MATLAB calculates the color data as the average temperature for each month.

How is heatmap calculated? ›

In a typical heatmap you have a raster, a matrix of datapoints, e.g. from 1:10 in one and 1:50 in the other dimension, these values can be categorical as well. Here no smoothing is applied, each point typically shows its own values. (Sometimes a clustering is applied and then the mean within this clusters are shown).

What is a heatmap data visualization? ›

By definition, heatmap visualization or heatmap data visualization is a method of graphically representing numerical data where the value of each data point is indicated using colors.

How to plot the heatmap? ›

Create a matrix of data. Then create a heatmap of the matrix values. Use custom labels along the x-axis and y-axis by specifying the first two input arguments as the labels you want.

What color is missing data in MATLAB heatmap? ›

Missing data points are colored gray in the heatmap. If data points are missing, you can use this property to impute the missing values.

How many variables in a heatmap? ›

Heatmaps are used to show relationships between two variables, one plotted on each axis. By observing how cell colors change across each axis, you can observe if there are any patterns in value for one or both variables.

What is the limit of heatmap? ›

Heatmaps limitations

Heat maps data is retained for up to 13 months. Heat maps are limited to up to 100,000 page views per heat map.

Why use Z score for heatmap? ›

Z-scores (standard scores) are often used in heatmaps to standardize data and make it comparable across different markers or conditions. Here are some considerations: Advantages of using z-scores: Normalization: Z-scores standardize data by subtracting the mean and dividing by the standard deviation.

What is the format of a heatmap? ›

Heatmap (Matrix)

Typically, all the rows are one category (labels displayed on the left or right side) and all the columns are another category (labels displayed on the top or bottom). The individual rows and columns are divided into the subcategories, which all match up with each other in a matrix.

How to analyze a heatmap? ›

Analysis has multiple steps. First you need to read your heatmap, then identify the specific sections that are “working” and which aren't. Create a hypothesis as to why a certain section is or isn't working, then build a new design and see if it improves your users' experience.

How to create a heat map for free? ›

How to create a heatmap (for free) A heatmap (or heat map) is a color-coded data visualization, usually with a color scale gradient from blue (cold) to red (hot). You can create a data heatmap with spreadsheet tools like Excel, or generate a website heatmap using a free heatmap tool like Hotjar.

What is heatmap algorithm? ›

AI-Generation Attention: AI-generated attention heat maps help visualize where the visiting user's attention will go on a certain section of a webpage. These types of heat maps are implemented using a created software algorithm to determine and predict the attention actions of the user.

How to interpret heatmap correlation? ›

In a correlation heatmap, each variable is represented by a row and a column, and the cells show the correlation between them. The color of each cell represents the strength and direction of the correlation, with darker colors indicating stronger correlations.

How to create thermal model in MATLAB? ›

Create and Populate Thermal Model

Create the geometry and include it in the model. Assign material properties. Specify that the entire geometry generates heat at the rate of 25. Apply insulated boundary conditions on three edges and the free convection boundary condition on the right edge.

How to plot a 2D map in MATLAB? ›

plot( X , Y ) creates a 2-D line plot of the data in Y versus the corresponding values in X .
  1. To plot a set of coordinates connected by line segments, specify X and Y as vectors of the same length.
  2. To plot multiple sets of coordinates on the same set of axes, specify at least one of X or Y as a matrix.

How to create a path in MATLAB? ›

On the Home tab, in the Environment section, click Set Path. The Set Path dialog box appears. Alternatively, you can access this dialog box using the pathtool function. Use the Add Folder or Add Folder with Subfolders button to add new folders to MATLAB search path.

How to create charts in MATLAB? ›

How to Plot a Graph in MATLAB
  1. Step 1: Specify the Range of Values for the x variable for which you're plotting the function. ...
  2. Step 2: Define the function, y = f(x)
  3. Step 3: Use the plot function to generate a figure.
  4. Step 1: Use the functions xlabel, ylabel, and title to generate labels along the axes.
  5. Display grid lines.
Jun 22, 2022

References

Top Articles
Latest Posts
Article information

Author: Arline Emard IV

Last Updated:

Views: 6147

Rating: 4.1 / 5 (52 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Arline Emard IV

Birthday: 1996-07-10

Address: 8912 Hintz Shore, West Louie, AZ 69363-0747

Phone: +13454700762376

Job: Administration Technician

Hobby: Paintball, Horseback riding, Cycling, Running, Macrame, Playing musical instruments, Soapmaking

Introduction: My name is Arline Emard IV, I am a cheerful, gorgeous, colorful, joyous, excited, super, inquisitive person who loves writing and wants to share my knowledge and understanding with you.