[R] Remove NAs from Barplot

Marc Schwartz (via MN) mschwartz at mn.rr.com
Wed Aug 24 19:29:21 CEST 2005


On Wed, 2005-08-24 at 13:06 -0400, Doran, Harold wrote:
> Dear List:
> 
> I'm creating a series of barplots using Sweave that must assume a
> standard format. This is student achievement data and the x-axis must
> include all grades 3 to 8. In some cases, the data for a grade (or more
> than one grade) are missing in the vector math.bar, but are never
> missing for the vector apmxpmeet. The following sample code illustrates
> the issue.
> 
> Using the code below to create the plot works fine. However, the
> following command is designed to place the data onto the plot:
> 
> text(math.barplot, graph.max+5, format(tot), xpd = TRUE, col = c("blue",
> "orange") )
> 
> This does work, but, it also places 'NA's on the plot. Is there a way to
> place the data onto the plot such that the numbers appear, but for the
> NAs not to appear?  I've searched through ?text but was not able to find
> a solution. 
> 
> math.bar <- c(NA,NA,NA,NA,55,48)
> apmxpmeet <- c(47, 50, 49, 50, 49, 46)
> 
> par(ps=10)
> math.bar <- rbind(math.bar, apmxpmeet)
> math.barplot <- barplot(math.bar, beside=T, col=c('blue','orange'),
> names=c('Grade \n 3','Grade \n 4','Grade \n 5','Grade \n 6','Grade \n
> 7','Grade \n 8'), 
> ylim=c(0,120), ylab="Percentage", xlab="Grade Level")
> tot <- round(math.bar,digits=0)
> graph.max <- max(math.bar, apmxpmeet, na.rm=T)
> text(math.barplot, graph.max+5, format(tot), xpd = TRUE, col = c("blue",
> "orange") )
> tmp$sch_nameS05 <- as.character(tmp$sch_nameS05)
> legend(2,120,legend=(c(tmp$sch_nameS05, "Average")),
> fill=c("blue","orange"))
> 
> Thanks,
> Harold


Harold,

Get rid of the 'format(tot)' in your text() call:

text(math.barplot, graph.max+5, tot, xpd = TRUE, 
     col = c("blue", "orange"))


By using format(tot), you are coercing the values to text. Thus:

> format(tot)
          [,1] [,2] [,3] [,4] [,5] [,6]
math.bar  "NA" "NA" "NA" "NA" "55" "48"
apmxpmeet "47" "50" "49" "50" "49" "46"

versus:

> tot
          [,1] [,2] [,3] [,4] [,5] [,6]
math.bar    NA   NA   NA   NA   55   48
apmxpmeet   47   50   49   50   49   46


In the first case, text() will draw "NA", whereas in the second, the NA
is ignored.

Also, your code above is not entirely reproducible, since:

> tmp$sch_nameS05 <- as.character(tmp$sch_nameS05)
Error: Object "tmp" not found


HTH,

Marc Schwartz




More information about the R-help mailing list