stackedplot
Stacked plot of several variables with common x-axis
Syntax
Description
stackedplot(
plots the variables of a
table or timetable in a stacked plot, up to a maximum of 25 variables. The function plots
the variables in separate y-axes, stacked vertically. The variables
share a common x-axis.tbl
)
If
tbl
is a table, then the function plots the variables against row numbers.If
tbl
is a timetable, then the function plots the variables against row times.
The stackedplot
function plots all the numeric, logical,
categorical, datetime, and duration variables of tbl
, and ignores table
variables having any other data type.
stackedplot(___,'XVariable',
specifies the table variable that provides the x-values for the
stacked plot. This syntax supports only tables, and not timetables.xvar
)
stackedplot(
plots the columns of
Y
)Y
versus their row number. The x-axis scale
ranges from 1 to the number of rows in Y
.
stackedplot(___,
sets
the line style, marker symbol, and color. You can use this syntax with the input arguments
of any of the previous syntaxes.LineSpec
)
stackedplot(___,
sets
properties for the stacked plot using one or more Name,Value
)Name,Value
pair
arguments. For a list of the properties, see StackedLineChart Properties. Use this option with any of the input argument combinations in the
previous syntaxes. Name-value pair settings apply to all the plots in the stacked plot.
Enclose each property name in quotes.
stackedplot(
creates
the stacked plot in the figure, panel, or tab specified by parent
,___)parent
. The
option parent
can precede any of the input argument combinations in the
previous syntaxes.
returns a
s
= stackedplot(___)StackedLineChart
object. You can use s
to change
properties of the stacked plot after you have created it. For a list of properties, see
StackedLineChart Properties.
Examples
Plot Timetable Variables
Read data from a spreadsheet to a timetable. (Read any text data it contains into string arrays). The first variable that contains dates and times, OutageTime
, provides the row times for the timetable. Display the first five rows.
tbl = readtimetable("outages.csv","TextType","string"); head(tbl,5)
ans=5×5 timetable
OutageTime Region Loss Customers RestorationTime Cause
________________ ___________ ______ __________ ________________ _________________
2002-02-01 12:18 "SouthWest" 458.98 1.8202e+06 2002-02-07 16:50 "winter storm"
2003-01-23 00:49 "SouthEast" 530.14 2.1204e+05 NaT "winter storm"
2003-02-07 21:15 "SouthEast" 289.4 1.4294e+05 2003-02-17 08:14 "winter storm"
2004-04-06 05:44 "West" 434.81 3.4037e+05 2004-04-06 06:10 "equipment fault"
2002-03-16 06:18 "MidWest" 186.44 2.1275e+05 2002-03-18 23:23 "severe storm"
Sort the timetable so that its row times are in order. The row times of a timetable do not need to be in order. However, if you use the row times as the x-axis of a plot, then it is better to ensure the timetable is sorted by its row times.
tbl = sortrows(tbl); head(tbl,5)
ans=5×5 timetable
OutageTime Region Loss Customers RestorationTime Cause
________________ ___________ ______ __________ ________________ ______________
2002-02-01 12:18 "SouthWest" 458.98 1.8202e+06 2002-02-07 16:50 "winter storm"
2002-03-05 17:53 "MidWest" 96.563 2.8666e+05 2002-03-10 14:41 "wind"
2002-03-16 06:18 "MidWest" 186.44 2.1275e+05 2002-03-18 23:23 "severe storm"
2002-03-26 01:59 "MidWest" 388.04 5.6422e+05 2002-03-28 19:55 "winter storm"
2002-04-20 16:46 "MidWest" 23141 NaN NaT "unknown"
Create a stacked plot of data from tbl
. The row times, OutageTime
, provide the values along the x-axis. The stackedplot
function plots the values from the Loss
, Customers
, and RestorationTime
variables, with each variable plotted along its own y-axis. However, the plot does not include the Region
and Cause
variables because they contain data that cannot be plotted.
stackedplot(tbl)
Specify Variables
Create a table from patient data. Display the first three rows.
tbl = readtable("patients.xls","TextType","string"); head(tbl,3)
ans=3×10 table
LastName Gender Age Location Height Weight Smoker Systolic Diastolic SelfAssessedHealthStatus
__________ ________ ___ ___________________________ ______ ______ ______ ________ _________ ________________________
"Smith" "Male" 38 "County General Hospital" 71 176 true 124 93 "Excellent"
"Johnson" "Male" 43 "VA Hospital" 69 163 false 109 77 "Fair"
"Williams" "Female" 38 "St. Mary's Medical Center" 64 131 false 125 83 "Good"
Plot only four of the variables from the table.
stackedplot(tbl,["Height","Weight","Systolic","Diastolic"])
Reorder Variables
Read a timetable from file and display its first three rows.
tbl = readtimetable("outages.csv","TextType","string"); tbl = sortrows(tbl); head(tbl,3)
ans=3×5 timetable
OutageTime Region Loss Customers RestorationTime Cause
________________ ___________ ______ __________ ________________ ______________
2002-02-01 12:18 "SouthWest" 458.98 1.8202e+06 2002-02-07 16:50 "winter storm"
2002-03-05 17:53 "MidWest" 96.563 2.8666e+05 2002-03-10 14:41 "wind"
2002-03-16 06:18 "MidWest" 186.44 2.1275e+05 2002-03-18 23:23 "severe storm"
Reorder the variables by specifying them in an order that differs from their order in the table. For example, RestorationTime
is the last variable in the timetable that can be plotted. By default, stackedplot
places it at the bottom of the plot. But you can reorder the variables to put RestorationTime
at the top.
stackedplot(tbl,["RestorationTime","Loss","Customers"])
There are also other ways to reorder the variables.
Specify them by their numeric order in the table:
stackedplot(tbl,[4 2 3]);
Return a
StackedLineChart
object and reorder the values in itsDisplayVariables
property:s = stackedplot(tbl); s.DisplayVariables = ["RestorationTime","Loss","Customers"]
Plot Multiple Variables Using One Y-Axis
Create a table from a subset of patient data, using the Weight
, Systolic
, and Diastolic
variables.
load patients
tbl = table(Weight,Systolic,Diastolic);
head(tbl,3)
ans=3×3 table
Weight Systolic Diastolic
______ ________ _________
176 124 93
163 109 77
131 125 83
Create a stacked plot, with Systolic
and Diastolic
plotted using the same y-axis, and Weight
using its own y-axis. First, specify vars
as a cell array with two elements. The first element groups "Systolic"
and "Diastolic"
together in a string array. They are plotted together on a common y-axis. The second element of the cell array is "Weight"
. It is plotted on its own y-axis.
vars = {["Systolic","Diastolic"],"Weight"}
vars=1×2 cell array
{["Systolic" "Diastolic"]} {["Weight"]}
stackedplot(tbl,vars)
Plot Columns of Matrix
Create a numeric matrix and a numeric vector.
X = [0:4:20]
X = 1×6
0 4 8 12 16 20
Y = randi(100,6,3)
Y = 6×3
82 28 96
91 55 49
13 96 81
92 97 15
64 16 43
10 98 92
Create a stacked plot using X
and Y
.
stackedplot(X,Y)
Specify Title and Labels Using Name-Value Arguments
Load a timetable that has a set of weather measurements. Display its first three rows.
load outdoors
outdoors(1:3,:)
ans=3×3 timetable
Time Humidity TemperatureF PressureHg
___________________ ________ ____________ __________
2015-11-15 00:00:24 49 51.3 29.61
2015-11-15 01:30:24 48.9 51.5 29.61
2015-11-15 03:00:24 48.9 51.5 29.61
Create a stacked plot. Specify the title and labels for the y-axes using name-value arguments. You can use name-value arguments to change any properties from their defaults values. (Also note that you can specify the degree symbol using char(176)
.)
degreeSymbol = char(176); newYlabels = ["RH (%)","T (" + degreeSymbol + "F)","P (in Hg)"]; stackedplot(outdoors,"Title","Weather Data","DisplayLabels",newYlabels)
Change Individual Plots to Scatter and Stair Plots
The stackedplot
function returns a StackedLineChart
object. You can use it to set the same property value for all plots, or to set different property values for individual plots. In this example, first change the line widths for all plots in a stacked plot. Then, use the PlotType
property of individual plots, so that the stacked plot has a line plot, scatter plot, and stair plot.
Load a timetable that has a set of weather measurements.
load outdoors
outdoors(1:3,:)
ans=3×3 timetable
Time Humidity TemperatureF PressureHg
___________________ ________ ____________ __________
2015-11-15 00:00:24 49 51.3 29.61
2015-11-15 01:30:24 48.9 51.5 29.61
2015-11-15 03:00:24 48.9 51.5 29.61
Create a stacked plot and return a StackedLineChart
object.
s = stackedplot(outdoors)
s = StackedLineChart with properties: SourceTable: [51x3 timetable] DisplayVariables: {'Humidity' 'TemperatureF' 'PressureHg'} Color: [0 0.4470 0.7410] LineStyle: '-' LineWidth: 0.5000 Marker: 'none' MarkerSize: 6 Show all properties
The object provides access to many properties that apply to all of the plots. For example, you can use s.LineWidth
to make the lines wider.
s.LineWidth = 2;
The object also provides access to arrays of objects that you can use to modify the lines and y-axes for individual plots. To access properties of individual lines, use s.LineProperties
. For each plot, you can specify a different line style, marker, plot type, and so on.
s.LineProperties
ans=3×1 object
3x1 StackedLineProperties array with properties:
Color
MarkerFaceColor
MarkerEdgeColor
LineStyle
LineWidth
Marker
MarkerSize
PlotType
Change the second plot to a scatter plot, and the third plot to a stair plot, using the PlotType
property.
s.LineProperties(2).PlotType = "scatter"; s.LineProperties(3).PlotType = "stairs";
You also can access individual y-axes through the s.AxesProperties
property.
s.AxesProperties
ans=3×1 object
3x1 StackedAxesProperties array with properties:
YLimits
YScale
LegendLabels
LegendLocation
LegendVisible
For example, change the y-limits of the first plot.
s.AxesProperties(1).YLimits = [46 54];
Semilog Plot with Y-Axis Log Scale
Import data into a timetable. Then make a stacked plot. By default, all plots have linear scales on both their x- and y-axes.
tbl = readtimetable("outages.csv");
tbl = sortrows(tbl);
s = stackedplot(tbl)
s = StackedLineChart with properties: SourceTable: [1468x5 timetable] DisplayVariables: {'Loss' 'Customers' 'RestorationTime'} Color: [0 0.4470 0.7410] LineStyle: '-' LineWidth: 0.5000 Marker: 'none' MarkerSize: 6 Show all properties
You can access properties of individual y-axes, such as their scales, through the s.AxesProperties
property.
s.AxesProperties
ans=3×1 object
3x1 StackedAxesProperties array with properties:
YLimits
YScale
LegendLabels
LegendLocation
LegendVisible
To turn the first and second plots into semilog plots, with log scales on their y-axes, set their YScale
properties to 'log'
.
s.AxesProperties(1).YScale = 'log'; s.AxesProperties(2).YScale = 'log';
Input Arguments
tbl
— Input table or timetable
table | timetable
Input table or timetable.
vars
— Variables in input table or timetable
string array | numeric array | logical array | cell array
Variables in the input table, specified as a string array, numeric array, or logical array, or cell array.
If vars
is a cell array, then it can be a cell array of character
vectors (where each character vector names one variable), or it also can be a nested
cell array (where each element of the cell array is an array that groups together
multiple variables). For example, if vars = {'A','B','C'}
, then
variables A
, B
, and C
are each
plotted on their own y-axes. But if vars =
{["A","B"],"C"}
, then A
and B
are
plotted together on one y-axis, and C
is plotted
on a second y
-axis.
xvar
— Table variable that contains x-values
string scalar | character vector | integer | logical array
Table variable that contains x-values, specified as a string scalar, character vector, integer, or logical array.
You can specify xvar
only when the input argument
tbl
is a table, not a timetable.
X
— x-values
numeric vector | datetime vector | duration vector | logical vector
x-values, specified as a numeric, datetime, duration, or
logical vector. The length of X
must equal the number of rows of
Y
.
Y
— y-values
numeric array | datetime array | duration array | categorical array | logical array
y-values, specified as a numeric, datetime, duration,
categorical, or logical array. The stackedplot
function plots each
column in a separate y-axis.
LineSpec
— Line style, marker, and color
character vector | string
Line style, marker, and color, specified as a character vector or string containing symbols. The symbols can appear in any order. You do not need to specify all three characteristics (line style, marker, and color). For example, if you omit the line style and specify the marker, then the plot shows only the marker and no line.
Example: '--or'
is a red dashed line with circle markers
Line Style | Description | Resulting Line |
---|---|---|
'-' | Solid line |
|
'--' | Dashed line |
|
':' | Dotted line |
|
'-.' | Dash-dotted line |
|
Marker | Description | Resulting Marker |
---|---|---|
'o' | Circle |
|
'+' | Plus sign |
|
'*' | Asterisk |
|
'.' | Point |
|
'x' | Cross |
|
'_' | Horizontal line |
|
'|' | Vertical line |
|
's' | Square |
|
'd' | Diamond |
|
'^' | Upward-pointing triangle |
|
'v' | Downward-pointing triangle |
|
'>' | Right-pointing triangle |
|
'<' | Left-pointing triangle |
|
'p' | Pentagram |
|
'h' | Hexagram |
|
Color Name | Short Name | RGB Triplet | Appearance |
---|---|---|---|
'red' | 'r' | [1 0 0] |
|
'green' | 'g' | [0 1 0] |
|
'blue' | 'b' | [0 0 1] |
|
'cyan'
| 'c' | [0 1 1] |
|
'magenta' | 'm' | [1 0 1] |
|
'yellow' | 'y' | [1 1 0] |
|
'black' | 'k' | [0 0 0] |
|
'white' | 'w' | [1 1 1] |
|
parent
— Parent 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: 'Marker','o','MarkerSize',10
The stacked chart line properties listed here are only a subset common to all stacked plots, whether the data source is a table or array. For a complete list, see StackedLineChart Properties.
Color
— Line color
[0 0.4470 0.7410]
(default) | RGB triplet | hexadecimal color code | 'r'
| 'g'
| 'b'
| ...
Line color, specified as an RGB triplet, a hexadecimal color code, or one of the color options listed in the first table.
For a custom color, specify an RGB triplet or a hexadecimal color code.
An RGB triplet is a three-element row vector whose elements specify the intensities of the red, green, and blue components of the color. The intensities must be in the range
[0,1]
; for example,[0.4 0.6 0.7]
.A hexadecimal color code is a character vector or a string scalar that starts with a hash symbol (
#
) followed by three or six hexadecimal digits, which can range from0
toF
. The values are not case sensitive. Thus, the color codes'#FF8800'
,'#ff8800'
,'#F80'
, and'#f80'
are equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options, the equivalent RGB triplets, and hexadecimal color codes.
Color Name | Short Name | RGB Triplet | Hexadecimal Color Code | Appearance |
---|---|---|---|---|
'red' | 'r' | [1 0 0] | '#FF0000' | |
'green' | 'g' | [0 1 0] | '#00FF00' | |
'blue' | 'b' | [0 0 1] | '#0000FF' | |
'cyan'
| 'c' | [0 1 1] | '#00FFFF' | |
'magenta' | 'm' | [1 0 1] | '#FF00FF' | |
'yellow' | 'y' | [1 1 0] | '#FFFF00' | |
'black' | 'k' | [0 0 0] | '#000000' | |
'white' | 'w' | [1 1 1] | '#FFFFFF' | |
'none' | Not applicable | Not applicable | Not applicable | No color |
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB® uses in many types of plots.
RGB Triplet | Hexadecimal Color Code | Appearance |
---|---|---|
[0 0.4470 0.7410] | '#0072BD' | |
[0.8500 0.3250 0.0980] | '#D95319' | |
[0.9290 0.6940 0.1250] | '#EDB120' | |
[0.4940 0.1840 0.5560] | '#7E2F8E' | |
[0.4660 0.6740 0.1880] | '#77AC30' | |
[0.3010 0.7450 0.9330] | '#4DBEEE' | |
[0.6350 0.0780 0.1840] | '#A2142F' |
Example: 'blue'
Example: [0 0 1]
Example: '#0000FF'
LineStyle
— Line style
'-'
(default) | '--'
| ':'
| '-.'
| 'none'
Line style, specified as one of the options listed in this table.
Line Style | Description | Resulting Line |
---|---|---|
'-' | Solid line |
|
'--' | Dashed line |
|
':' | Dotted line |
|
'-.' | Dash-dotted line |
|
'none' | No line | No line |
LineWidth
— Line width
0.5
(default) | positive value
Line width, specified as a positive value in points, where 1 point = 1/72 of an inch. If the line has markers, then the line width also affects the marker edges.
The line width cannot be thinner than the width of a pixel. If you set the line width to a value that is less than the width of a pixel on your system, the line displays as one pixel wide.
Marker
— Marker symbol
'none'
(default) | 'o'
| '+'
| '*'
| '.'
| ...
Marker symbol, specified as one of the values listed in this table. By default, the object does not display markers. Specifying a marker symbol adds markers at each data point or vertex.
Marker | Description | Resulting Marker |
---|---|---|
'o' | Circle |
|
'+' | Plus sign |
|
'*' | Asterisk |
|
'.' | Point |
|
'x' | Cross |
|
'_' | Horizontal line |
|
'|' | Vertical line |
|
's' | Square |
|
'd' | Diamond |
|
'^' | Upward-pointing triangle |
|
'v' | Downward-pointing triangle |
|
'>' | Right-pointing triangle |
|
'<' | Left-pointing triangle |
|
'p' | Pentagram |
|
'h' | Hexagram |
|
'none' | No markers | Not applicable |
MarkerSize
— Marker size
6
(default) | positive value
Marker size, specified as a positive value in points, where 1 point = 1/72 of an inch.
Output Arguments
s
— Stacked line chart object
StackedLineChart
object
StackedLineChart
object, which is a standalone visualization.
Use s
to set properties on the stacked plot after creating it.
More About
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 stacked plot, use these features.
Zoom — Use the scroll wheel to zoom.
Pan — Click and drag the stacked plot to pan across the x-values.
Data cursor — Hover over a location to display y-values for each plot.
Version History
Introduced in R2018bR2022a: R2022a: Plot a variable multiple times in a stacked plot
Behavior changed in R2022a
Starting in R2022a, you can display the same table or timetable variable multiple times in a stacked plot. In previous releases, specifying a variable more than once results in an error.
For example, create a timetable from the outages.csv
file. Then plot
the RestorationTime
variable under each of the other variables you
specify.
tbl = readtimetable("outages.csv"); tbl = sortrows(tbl); stackedplot(tbl,["Loss","RestorationTime","Customers","RestorationTime"])
See Also
Functions
Properties
Open Example
You have a modified version of this example. Do you want to open this example with your edits?
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.
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:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
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
- United Kingdom (English)