Main Content

bar

  • Bar graph

Description

example

bar(y)creates a bar graph with one bar for each element iny. Ifyis anm-by-nmatrix, thenbarcreatesmgroupsofnbars.

example

bar(x,y)draws the bars at the locations specified byx.

example

bar(___,width)sets the relative bar width, which controls the separation of bars within a group. Specifywidthas a scalar value. Use this option with any of the input argument combinations in the previous syntaxes.

example

bar(___,style)specifies the style of the bar groups. For example, use'stacked'to display each group as one multicolored bar.

example

bar(___,color)sets the color for all the bars. For example, use'r'for red bars.

example

bar(___,Name,Value)specifies properties of the bar graph using one or more name-value pair arguments. Only bar graphs that use the default'grouped'or'stacked'style support setting bar properties. Specify the name-value pair arguments after all other input arguments. For a list of properties, seeBar Properties.

example

bar(ax,___)plots into the axes specified byaxinstead of into the current axes (gca). The optionaxcan precede any of the input argument combinations in the previous syntaxes.

example

b= bar(___)returns one or moreBarobjects. Ifyis a vector, thenbarcreates oneBarobject. Ifyis a matrix, thenbar返回一个Barobject for eachseries. Usebto set properties of the bars after displaying the bar graph.

Examples

collapse all

y = [75 91 105 123.5 131 150 179 203 226 249 281.5]; bar(y)

Figure contains an axes object. The axes object contains an object of type bar.

Specify the bar locations along thex-axis.

x = 1900:10:2000; y = [75 91 105 123.5 131 150 179 203 226 249 281.5]; bar(x,y)

Figure contains an axes object. The axes object contains an object of type bar.

Set the width of each bar to 40 percent of the total space available for each bar.

y = [75 91 105 123.5 131 150 179 203 226 249 281.5]; bar(y,0.4)

Figure contains an axes object. The axes object contains an object of type bar.

Display four groups of three bars.

y = [2 2 3; 2 5 6; 2 8 9; 2 11 12]; bar(y)

Figure contains an axes object. The axes object contains 3 objects of type bar.

Display one bar for each row of the matrix. The height of each bar is the sum of the elements in the row.

y = [2 2 3; 2 5 6; 2 8 9; 2 11 12]; bar(y,'stacked')

Figure contains an axes object. The axes object contains 3 objects of type bar.

Definexas a vector of three year values. Defineyas a matrix that contains a combination of negative and positive values. Display the values in a bar graph.

x = [1980 1990 2000]; y = [15 20 -5; 10 -17 21; -10 5 15]; bar(x,y,'stacked')

Figure contains an axes object. The axes object contains 3 objects of type bar.

One way to indicate categories for your bars is to specifyXas a categorical array. Thebarfunction uses a sorted list of the categories, so the bars might display in a different order than you expect. To preserve the order, call thereordercatsfunction.

DefineXas categorical array, and call thereordercatsfunction to specify the order for the bars. Then defineYas a vector of bar heights and display the bar graph.

X = categorical({'Small','Medium','Large','Extra Large'}); X = reordercats(X,{'Small','Medium','Large','Extra Large'}); Y = [10 21 33 52]; bar(X,Y)

Figure contains an axes object. The axes object contains an object of type bar.

Definevalsas a matrix containing the values of two data sets. Display the values in a bar graph and specify an output argument. Since there are two data sets,bar返回一个vector containing twoBarobjects.

x = [1 2 3]; vals = [2 3 6; 11 23 26]; b = bar(x,vals);

Figure contains an axes object. The axes object contains 2 objects of type bar.

Display the values at the tips of the first series of bars. Get the coordinates of the tips of the bars by getting theXEndPointsandYEndPointsproperties of the firstBarobject. Pass those coordinates to thetextfunction, and specify the vertical and horizontal alignment so that the values are centered above the tips of the bars.

xtips1 = b(1).XEndPoints; ytips1 = b(1).YEndPoints; labels1 = string(b(1).YData); text(xtips1,ytips1,labels1,'HorizontalAlignment','center',...'VerticalAlignment','bottom')

Figure contains an axes object. The axes object contains 5 objects of type bar, text.

Next, display the values above the tips of the second series of bars.

xtips2 = b(2).XEndPoints; ytips2 = b(2).YEndPoints; labels2 = string(b(2).YData); text(xtips2,ytips2,labels2,'HorizontalAlignment','center',...'VerticalAlignment','bottom')

Figure contains an axes object. The axes object contains 8 objects of type bar, text.

Starting in R2019b, you can display a tiling of bar graphs using thetiledlayoutandnexttilefunctions. Call thetiledlayoutfunction to create a 2-by-1 tiled chart layout. Call thenexttilefunction to create the axes objectsax1andax2. Display a bar graph in the top axes. In the bottom axes, display a stacked bar graph of the same data.

y = [1 2 3; 4 5 6]; tiledlayout(2,1)% Top bar graphax1 = nexttile; bar(ax1,y)% Bottom bar graphax2 = nexttile; bar(ax2,y,'stacked')

Figure contains 2 axes objects. Axes object 1 contains 3 objects of type bar. Axes object 2 contains 3 objects of type bar.

Create a bar graph using red bars.

y = [75 91 105 123.5 131 150 179 203 226 249 281.5]; bar(y,'r')

Figure contains an axes object. The axes object contains an object of type bar.

Set the bar interior color and outline color using RGB triplets. Set the width of the bar outline.

y = [75 91 105 123.5 131 150 179 203 226 249 281.5]; bar(y,'FaceColor',[0 .5 .5],'EdgeColor',[0 .9 .9],'LineWidth',1.5)

Figure contains an axes object. The axes object contains an object of type bar.

Control individual bar colors using theCDataproperty of theBarobject.

Create a bar chart and assign theBarobject to a variable. Set theFaceColorproperty of theBarobject to'flat'so that the chart uses the colors defined in theCDataproperty. By default, theCDataproperty is prepopulated with a matrix of the default RGB color values. To change a particular color, change the corresponding row in the matrix. For example, change the color of the second bar.

b = bar(rand(10,1)); b.FaceColor ='flat'; b.CData(2,:) = [.5 0 .5];

Figure contains an axes object. The axes object contains an object of type bar.

Create a bar chart that uses colormap colors by setting theFaceColorproperty to'flat'. Then set theCDataproperty for eachBarobject to an integer.

y = [1 3 5; 3 2 7; 3 4 2]; b = bar(y,'FaceColor','flat');fork = 1:size(y,2) b(k).CData = k;end

Figure contains an axes object. The axes object contains 3 objects of type bar.

Create matrixy, where each column is a series of data. Call thebarfunction to display the data in a bar graph, and specify an output argument. The output is a vector of threeBarobjects, where each object corresponds to a different series. This is true whether the bars are grouped or stacked.

y = [10 15 20; 30 35 40; 50 55 62]; b = bar(y);

Figure contains an axes object. The axes object contains 3 objects of type bar.

Make the third series of bars green.

b(3).FaceColor = [.2 .6 .5];

Figure contains an axes object. The axes object contains 3 objects of type bar.

Input Arguments

collapse all

x-coordinates, specified as a scalar, vector, or matrix. The values ofxdo not need to be in order, but the size ofxdepends on the size ofyand how you want to display your data. This table describes the most common situations.

Presentation How to Specify X and Y Example
Display one series of bars.

Specifyxandyas vectors that are the same length. The values inxmust be unique, but the values inydo not need to be unique.

x = [1980 1990 2000]; y = [10 20 30]; bar(x,y)

Bar chart containing one series of bars. One blue bar is displayed at each location in x.

Display multiple series of bars in groups.

Specify either of these combinations:

  • Specifyxandyas matrices of equal size. Each column ofycorresponds to a series of bars. By default, each series is a different color. To ensure consistent placement of the groups, specify the columns ofxas identical vectors. The values within a column must be unique, even though the columns are repeated.

  • Specifyxas a vector of unique values, and specifyyas a matrix. The length ofxmust equal the length of at least one dimension ofy. The other dimension ofycontains values for the different series of bars.

x = [1980 1980 1980 1990 1990 1990]; y = [2 6 9 11 22 32]; bar(x,y)
Or
x = [1980 1990]; y = [2 6 9 11 22 32]; bar(x,y)

Bar chart containing three series of bars. Each location in x has a group of three bars. The first bar in each group is dark blue, the second bar is dark orange, and the third bar is dark yellow.

Display one group of bars centered at onexvalue.

Specifyxas a scalar andyas a vector.

x = 1990; y = [10 20 30]; bar(x,y)

Bar chart containing one group of bars at the specified x location. The first bar is dark blue, the second bar is dark orange, and the third bar is dark yellow.

Data Types:single|double|int8|int16|int32|int64|uint8|uint16|uint32|uint64|categorical|datetime|duration

y-coordinates, specified as a scalar, vector, or matrix. The size ofydepends on the size ofxand how you want to display your data. This table describes the most common situations.

Presentation How to Specify X and Y Example
Display one series of bars.

Specifyxandyas vectors that are the same length. The values inxmust be unique, but the values inydo not need to be unique.

x = [1980 1990 2000]; y = [10 20 30]; bar(x,y)

Bar chart containing one series of bars. One blue bar is displayed at each location in x.

Display multiple series of bars in groups.

Specify either of these combinations:

  • Specifyxandyas matrices of equal size. Each column ofycorresponds to a series of bars. By default, each series is a different color. To ensure consistent placement of the groups, specify the columns ofxas identical vectors. The values within a column must be unique, even though the columns are repeated.

  • Specifyxas a vector of unique values, and specifyyas a matrix. The length ofxmust equal the length of at least one dimension ofy. The other dimension ofycontains values for the different series of bars.

x = [1980 1980 1980 1990 1990 1990]; y = [2 6 9 11 22 32]; bar(x,y)
Or
x = [1980 1990]; y = [2 6 9 11 22 32]; bar(x,y)

Bar chart containing three series of bars. Each location in x has a group of three bars. The first bar in each group is dark blue, the second bar is dark orange, and the third bar is dark yellow.

Display one group of bars centered at onexvalue.

Specifyxas a scalar andyas a vector.

x = 1990; y = [10 20 30]; bar(x,y)

Bar chart containing one group of bars at the specified x location. The first bar is dark blue, the second bar is dark orange, and the third bar is dark yellow.

Data Types:single|double|int8|int16|int32|int64|uint8|uint16|uint32|uint64|duration

Bar width, specified as a fraction of the total space available for each bar. The default of0.8means the bar width is 80% of the space from the previous bar to the next bar, with 10% of that space on each side.

If the width is1, then the bars within a group touch one another.

Example:bar([1 2 3],0.5)creates bars that use 50% of the available space.

Data Types:single|double|int8|int16|int32|int64|uint8|uint16|uint32|uint64

Group style, specified by one of these values.

Style Result Example

'grouped'

Display each group as adjacent bars that are centered around their correspondingxvalue.

Bar chart containing three series of bars. Each location in x has a group of three bars. The first bar in each group is dark blue, the second bar is dark orange, and the third bar is dark yellow.

'stacked'

Display each group as one multicolored bar. The length of a bar is the sum of the elements in the group.

Ifyis a vector, then the result is the same as'grouped'.

Bar chart containing three series of bars that are stacked. Each location in x has one bar that has three different colored sections.

'histc'

Display the bars in histogram format, in which the bars in a group touch one another. The trailing edge of each group is aligned with the correspondingxvalue.

Note

A better way to display a histogram is to call thehistogramfunction.

条形图包含四个系列的酒吧嗨stogram format. Each location in x has a group of four bars. The first bar in each group is dark blue, the second bar light blue, the third bar is green, and the fourth bar is yellow.

'hist'

Display the bars in histogram format. Each group is centered at the correspondingxvalue.

Note

A better way to display a histogram is to call thehistogramfunction.

条形图包含四个系列的酒吧嗨stogram format. Each location in x has a group of four bars. The first bar in each group is dark blue, the second bar light blue, the third bar is green, and the fourth bar is yellow.

Bar color, specified as one of the colors in this table.

Color Color
'b' Blue
'r' Red
'g' Green
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White

Axes object. If you do not specify an axes, thenbaruses the current axes for the bar graph.

Name-Value Arguments

Specify optional comma-separated pairs ofName,Valuearguments.Nameis the argument name andValueis the corresponding value.Namemust appear inside quotes. You can specify several name and value pair arguments in any order asName1,Value1,...,NameN,ValueN.

Example:bar([10 20 30],'EdgeColor','g')specifies a green outline around the bars.

TheBarproperties listed here are only a subset. For a complete list, seeBar Properties.

Note

  • The properties listed here are only a subset. For a complete list, seeBar Properties.

  • You can set these properties only on bar graphs that use the default'grouped'or'stacked'style.

Outline color, specified as'flat', an RGB triplet, a hexadecimal color code, a color name, or a short name. If there are 150 bars or fewer, the default value is[0 0 0], which corresponds to black. If there are more than 150 adjacent bars, the default value is'none'.

Starting in R2017b, the'flat'option uses theCDatavalues to color the edges. In previous releases, the'flat'option colored the edges using colors from the colormap.

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

Sample of the color red

'green' 'g' [0 1 0] '#00FF00'

Sample of the color green

'blue' 'b' [0 0 1] '#0000FF'

Sample of the color blue

'cyan' 'c' [0 1 1] '#00FFFF'

Sample of the color cyan

'magenta' 'm' [1 0 1] '#FF00FF'

Sample of the color magenta

'yellow' 'y' [1 1 0] '#FFFF00'

Sample of the color yellow

'black' 'k' [0 0 0] '#000000'

Sample of the color black

'white' 'w' [1 1 1] '#FFFFFF'

Sample of the color white

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

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] '#D95319'

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] '#EDB120'

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] '#7E2F8E'

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] '#77AC30'

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] '#4DBEEE'

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] '#A2142F'

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example:b = bar(1:10,'EdgeColor','red')

Example:b.EdgeColor = [0 0.5 0.5];

Example:b.EdgeColor = 'flat';

Example:b.EdgeColor = '#D2F9A7';

Fill color, specified as'flat', an RGB triplet, a hexadecimal color code, a color name, or a short name. The'flat'option uses theCDataproperty value of theBarobject to color the faces.

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

Sample of the color red

'green' 'g' [0 1 0] '#00FF00'

Sample of the color green

'blue' 'b' [0 0 1] '#0000FF'

Sample of the color blue

'cyan' 'c' [0 1 1] '#00FFFF'

Sample of the color cyan

'magenta' 'm' [1 0 1] '#FF00FF'

Sample of the color magenta

'yellow' 'y' [1 1 0] '#FFFF00'

Sample of the color yellow

'black' 'k' [0 0 0] '#000000'

Sample of the color black

'white' 'w' [1 1 1] '#FFFFFF'

Sample of the color white

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

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] '#D95319'

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] '#EDB120'

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] '#7E2F8E'

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] '#77AC30'

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] '#4DBEEE'

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] '#A2142F'

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Starting in R2017b, the default value is an RGB triplet from theColorOrderproperty of the axes. In previous releases, the default value was'flat'and the colors were based on the colormap.

Example:b = bar(1:10,'FaceColor','red')

Example:b.FaceColor = [0 0.5 0.5];

Example:b.FaceColor = 'flat';

Example:b.FaceColor = '#D2F9A7';

Color data, specified as one of these values:

  • RGB triplet — Single RGB color value applies to all bars.

  • Three-column matrix — One color per bar. Each row in the matrix specifies an RGB triplet for a particular bar.

  • Scalar — Single color applies to all bars, where the color comes from the colormap.

  • Vector — One color per bar. The colors come from the colormap.

By default, when you create a bar chart, theCDataproperty contains a three-column matrix of RGB triplets. You can change the color for a particular bar by changing the corresponding row in the matrix.

This property applies only when theFaceColororEdgeColorproperty is set to'flat'.

Example

Change the color for a particular bar by setting theFaceColorproperty to'flat'. Then change the corresponding row in theCDatamatrix to the new RGB triplet. For example, change the color of the second bar.

b = bar(1:10,'FaceColor','flat'); b.CData(2,:) = [0 0.8 0.8];

Bar chart that has all dark blue bars except the second bar, which is cyan.

Baseline value, specified as a numeric scalar value.

The baseline value that you specify applies to either thex-axis or they-axis depending on the bar chart orientation. If you change the orientation of the bar chart from vertical to horizontal, or vice versa, the baseline value might change. Set theBaseValueproperty after setting theHorizontalproperty.

Line style of bar outlines, specified as one of the line styles in this table.

Line Style Description Resulting Line
'-' Solid line

Sample of solid line

'--' Dashed line

Sample of dashed line

':' Dotted line

Sample of dotted line

'-.' Dash-dotted line

Sample of dash-dotted line, with alternating dashes and dots

'none' No line No line

Width of bar outlines, specified as a positive value in point units. One point equals 1/72 inch.

Example:1.5

Data Types:single|double|int8|int16|int32|int64|uint8|uint16|uint32|uint64

Output Arguments

collapse all

Barobjects. Use the elements inbto access and modify properties of a specificBarobject after it has been created. The number ofBarobjects depends on the size ofy. Ifyis a vector, thenbis oneBarobject. Ifyis a matrix, thenbis a vector containing aBar对象为每个系列y.

More About

collapse all

Series of Bars

A series consists of the bars at all locations inXfor a particular set of data. By default, each series of bars is indicated by a different color.

Group of Bars

A group consists of all the bars at a particular location inX.

Extended Capabilities

Introduced before R2006a