Session Ready
Exercise

Some plot functions also return useful information

As shown in the video, calling the barplot() function has the side effect of creating the plot we want, but it also returns a numerical vector with the center positions of each bar in the plot. This value is returned invisibly so we don't normally see it, but we can capture it with an assignment statement.

These return values can be especially useful when we want to overlay text on the bars of a horizontal barplot. Then, we capture the return values and use them as the y parameter in a subsequent call to the text() function, allowing us to place the text at whatever x position we want but overlaid in the middle of each horizontal bar. This exercise asks you to construct a horizontal barplot that exploits these possibilities.

Feel free to reference a similar example in the slides by clicking on the "Slides" tab next to the "R Console" tab.

Instructions
100 XP

The Cars93 data frame from the MASS package is already available in your workspace.

  • Use the table() function to generate the object tbl summarizing the number of records listing each value of the Cylinders variable from the Cars93 data frame.
  • Use the barplot() function with the horiz argument set to TRUE to construct a horizontal barplot of this record summary, specifying the color of the bars to be "transparent" and returning the vector mids giving the vertical positions of the centers of each bar in the plot. Specify the names.arg argument as "" to suppress the y-axis legend on this plot.
  • Use the text() function to label the Cylinders value for each bar in the barplot at the horizontal position 20. The names() function may prove useful here.
  • Use the text() function to list the counts for each cylinders value at the horizontal position 35. Here, the as.numeric() function may prove useful.