Use the
barplot function. The first argument is a vector of bar heights:> barplot(c(height1, height2, height3))
The
barplot function produces a simple bar chart. It assumes that the heights of your bars are conveniently stored in a vector. That is not always the case, however. Often, you have a vector of numeric data and a parallel factor that groups the data, and you want to produce a bar chart of the group means or the group totals. For example, the airquality dataset contains a numeric Temp column and a Month column. We can create a bar chart of the mean temperature by month in two steps. First, we compute the means:> heights <- tapply(airquality$Temp, airquality$Month, mean)
That gives the heights of the bars, from which we create the bar chart:
> barplot(heights)
The result is shown in the lefthand panel of Figure 1-4. The result is pretty bland, as you can see, so it’s common to add some simple adornments: a title, labels for the bars, and a label for the y-axis:
> barplot(heights,
+ main="Mean Temp. by Month",
+ names.arg=c("May", "Jun", "Jul", "Aug", "Sep"),
+ ylab="Temp (deg. F)")
The righthand panel of Figure 1-4 shows the improved bar chart.
The
barchart function in the lattice package is another way to produce a bar chart.This short, concise book provides beginners with a selection of how-to recipes to solve simple problems with R. Each solution gives you just what you need to know to get started with R for basic statistics, graphics, and regression. These solutions were selected from O'Reilly's R Cookbook, which contains more than 200 recipes for R that you'll find useful once you move beyond the basics.




Help






