Main Content

Plot Data Grouped by Category

Note

Thenominalandordinalarray data types are not recommended. To represent ordered and unordered discrete, nonnumeric data, use theCategorical Arraysdata type instead.

Plot Data Grouped by Category

This example shows how to plot data grouped by the levels of a categorical variable.

Load sample data.

loadcarsmall

The variableAccelerationcontains acceleration measurements on 100 sample cars. The variable起源is a character array containing the country of origin for each car.

Create a nominal array.

Convert起源to a nominal array.

起源= nominal(Origin); getlevels(Origin)
ans =1x6 nominal法国Germany Italy Japan Sweden USA

There are six unique countries of origin in the sample. By default,nominalorders the countries in ascending alphabetical order.

Plot data grouped by category.

Draw box plots forAcceleration, grouped by起源.

figure boxplot(Acceleration,Origin) title('Acceleration, Grouped by Country of Origin')

Figure contains an axes object. The axes object with title Acceleration, Grouped by Country of Origin contains 42 objects of type line.

The box plots appear in the same order as the categorical levels (usereorderlevelsto change the order of the categories).

Few observations have Italy as the country of origin.

Tabulate category counts.

Tabulate the number of sample cars from each country.

tabulate(Origin)
Value Count Percent France 4 4.00% Germany 9 9.00% Italy 1 1.00% Japan 15 15.00% Sweden 2 2.00% USA 69 69.00%

Only one car is made in Italy.

Drop a category.

Delete the Italian car from the sample.

Acceleration2 = Acceleration(Origin~='Italy'); Origin2 = Origin(Origin~='Italy'); getlevels(Origin2)
ans =1x6 nominal法国Germany Italy Japan Sweden USA

Even though the car from Italy is no longer in the sample, the nominal variable,起源2, still has the categoryItaly. Note that this is intentional—the levels of a categorical array do not necessarily coincide with the values.

下降一个类别的水平。

Usedroplevelsto remove theItalycategory.

起源2 = droplevels(Origin2,'Italy'); tabulate(Origin2)
Value Count Percent France 4 4.04% Germany 9 9.09% Japan 15 15.15% Sweden 2 2.02% USA 69 69.70%

TheItalycategory is no longer in the nominal array,起源2.

Plot data grouped by category.

Draw box plots ofAcceleration2, grouped by起源2.

figure boxplot(Acceleration2,Origin2) title('Acceleration, Grouped by Country of Origin')

Figure contains an axes object. The axes object with title Acceleration, Grouped by Country of Origin contains 35 objects of type line.

The plot no longer includes the car from Italy.

See Also

|||

Related Examples

More About