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.
Once again, we will use the citysales.csv
dataset and build upon the graph from the first recipe in this chapter.
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))
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.
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))
18.191.233.34