[R] barplot() x axes are not updated after removal of categories from the dataframe

Marc Schwartz marc_schwartz at comcast.net
Thu Feb 12 14:34:08 CET 2009

on 02/12/2009 06:35 AM R User R User wrote:
> Hi all,
> I'd be grateful for your help. I am a new user struggling with a barplot
> issue.
> I am plotting categories (X axis) and their mean count (Y axies) with
> barplot().
> The first call to barplot works fine.
> I remove records from the dataframe using final=[!final$varname == "some
> value",]
> I echo the dataframe and the records are no longer in the dataframe.
> When I call plot again however, the X axis still contains the removed
> category values albeit with a count of 0.
> How can I stop the removed categories appearing in the barplot? Are they
> stored globally after the first barplot call?
> thanks in advance for your help.
> R

When you subset a factor, the unused levels are not removed by default.
This is intentional to preserve these characteristics for subsequent
operations such as modeling.

You are presumably using something like:


to create the counts used in barplot().

As an example, using the iris dataset:

> table(iris$Species)

    setosa versicolor  virginica
        50         50         50

iris2 <- subset(iris, Species != "setosa")

> table(iris2$Species)

    setosa versicolor  virginica
         0         50         50

Note that even though I removed records from iris where Species ==
"setosa", it still shows in the table.

You would need to do the following:

iris2$Species <- factor(iris2$Species)

> table(iris2$Species)

versicolor  virginica
        50         50

Using factor() on the column removes the unused levels.

See  ?"[.factor" for more information.


Marc Schwartz

More information about the R-help mailing list