stackedplot

Stacked plot of several variables with common x-axis

Description

example

stackedplot(tbl) 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.

  • 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.

example

stackedplot(tbl,vars) plots only the table or timetable variables specified by vars.

stackedplot(___,'XVariable',xvar) specifies the table variable that provides the x-values for the stacked plot. This syntax supports only tables, and not timetables.

example

stackedplot(X,Y) plots the columns of Y versus the vector X up to a maximum of 25 columns.

stackedplot(Y) plots the columns of Y versus their row number. The x-axis scale ranges from 1 to the number of rows in Y.

stackedplot(___,LineSpec) sets the line style, marker symbol, and color. You can use this syntax with the input arguments of any of the previous syntaxes.

example

stackedplot(___,Name,Value) sets properties for the stacked plot using one or more 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(parent,___) creates the stacked plot in the figure, panel, or tab specified by parent. The option parent can precede any of the input argument combinations in the previous syntaxes.

example

s = stackedplot(___) returns a 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

collapse all

Read data from a spreadsheet to a table. Then convert the table to a timetable. The first variable that contains dates and times, OutageTime, provides the row times for the timetable. Display the first five rows.

tbl = readtable('outages.csv');
tbl = table2timetable(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'   }
    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)

Create a table from patient data. Display the first three rows.

tbl = readtable('patients.xls');
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'})

Create a timetable and display its first three rows.

tbl = readtable('outages.csv');
tbl = table2timetable(tbl);
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 its DisplayVariables property: s = stackedplot(tbl); s.DisplayVariables = {'RestorationTime','Loss','Customers'}

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. To plot variables together, specify them within a nested cell array.

vars = {{'Systolic','Diastolic'},'Weight'}
vars=1×2 cell array
    {1x2 cell}    {'Weight'}

stackedplot(tbl,vars)

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)

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 pair arguments. You can use name-values pairs 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)

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
    LegendLabels
    LegendLocation
    LegendVisible

Input Arguments

collapse all

Input table or timetable.

Variables in the input table, specified as a cell array of character vectors, string array, numeric array, or logical array.

If vars is a cell array, it also can be a nested cell array. The stackedplot function plots all the variables specified in a nested cell in the same y-axis.

Table variable that contains x-values, specified as a character vector, string scalar, integer, or logical array.

You can specify xvar only when the input argument tbl is a table, not a timetable.

x-values, specified as a numeric, datetime, duration, or logical vector. The length of X must equal the number of rows of Y.

y-values, specified as a numeric, datetime, duration, categorical, or logical array. The stackedplot function plots each column in a separate y-axis.

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 StyleDescription
-Solid line
--Dashed line
:Dotted line
-.Dash-dot line
MarkerDescription
'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
ColorDescription

y

yellow

m

magenta

c

cyan

r

red

g

green

b

blue

w

white

k

black

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

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

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.

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 from 0 to F. 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 NameShort NameRGB TripletHexadecimal Color CodeAppearance
'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 applicableNot applicableNot applicableNo color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB® uses in many types of plots.

RGB TripletHexadecimal Color CodeAppearance
[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'

Line style, specified as one of the options listed in this table.

Line StyleDescriptionResulting Line
'-'Solid line

'--'Dashed line

':'Dotted line

'-.'Dash-dotted line

'none'No lineNo line

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 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.

ValueDescription
'o'Circle
'+'Plus sign
'*'Asterisk
'.'Point
'x'Cross
'_'Horizontal line
'|'Vertical line
'square' or 's'Square
'diamond' or 'd'Diamond
'^'Upward-pointing triangle
'v'Downward-pointing triangle
'>'Right-pointing triangle
'<'Left-pointing triangle
'pentagram' or 'p'Five-pointed star (pentagram)
'hexagram' or 'h'Six-pointed star (hexagram)
'none'No markers

Marker size, specified as a positive value in points, where 1 point = 1/72 of an inch.

Output Arguments

collapse all

StackedLineChart object, which is a standalone visualization. Use s to set properties on the stacked plot 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 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.

Introduced in R2018b