Book Image

R Graphs Cookbook Second Edition

Book Image

R Graphs Cookbook Second Edition

Overview of this book

Table of Contents (22 chapters)
R Graphs Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Displaying values on top of or next to the bars


Sometimes, it is useful to have the exact values displayed on a bar chart to enable quick and accurate reading. There is no built-in function in R to do this. In this recipe, we will learn how to do this by writing some custom code.

Getting ready

Once again, we will use the citysales.csv dataset and build upon the graph from the first recipe in this chapter.

How to do it...

Let's make the graph with vertical bars and display the sales values just on top of the bars:

x<-barplot(as.matrix(citysales[,2:4]), beside=TRUE,
legend.text=citysales$City, args.legend=list(bty="n",horiz=TRUE),
col=brewer.pal(5,"Set1"),border="white",
ylim=c(0,100),ylab="Sales Revenue (1,000's of USD)",
main="Sales Figures")

y<-as.matrix(citysales[,2:4])

text(x,y+2,labels=as.character(y))

How it works...

In the example, we have used the text() function to label the bars with the corresponding values. To do so, we constructed two vectors, x and y, with the X and Y coordinates of the labels. We first created the barplot and saved it as an R object called x. When the result of the barplot() function call is assigned to an object, a vector that contains the X coordinates of the center of each of the bars is returned and saved in that object. You can verify this by typing in x at the R prompt and hitting the Enter key.

For the y vector, we created a matrix of the sales value columns. Finally, we passed the x and y values to text() as coordinates and set the label's argument to y values transformed into characters using the as.character() function. Note that we added 2 to each y value so that the labels are placed slightly above the bar. We might have to add a different value, depending on the scale of the graph.

There's more...

We can place the value labels next to the bars in a horizontal bar chart simply by swapping the x and y vectors in the text() function call:

y<-barplot(as.matrix(citysales[,2:4]), beside=TRUE,horiz=TRUE,
legend.text=citysales$City,args.legend=list(bty="n"),
col=brewer.pal(5,"Set1"),border="white",
xlim=c(0,100),xlab="Sales Revenue (1,000's of USD)",
main="Sales Figures")

x<-as.matrix(citysales[,2:4])

text(x+2,y,labels=as.character(x))

See also

In the next recipe, we will learn how to place text labels inside bars.