Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a tick mark, as well as xlab in a barplot panel in r

Tags:

graph

r

I would like to include tick marks in addition to xlab in a 3 by 3 panel of bar plots. I tried this solution for a single graph, but somehow I had trouble replicating it. The idea is to label each of the bars with d that runs from -3 to +3, with a unit increase. The first bar in each plot represents the value of -3. I tried to demonstrate my problem with a simulated data below. Any ideas?

# Data generation

# Populating a matrix
matrix(rnorm(63, 1:9), nrow=7, byrow=TRUE)

# Labelling the matrix
colnames(mat.s) <- c("Hs", "Sex", "Es", "Bo", "R", "W", "S", "Pri", "Abo")

# Tick mark indicator
d <- seq(-3,3,1)

# Plotting estimates
par(mfrow=c(3,3), mar = c(4,3,3,1))

for(i in 1:9) {

# Bar plot
barplot(mat.s[,i],

# X-label
xlab = colnames(mat.s)[i])

}
like image 917
AlxRd Avatar asked Dec 25 '22 11:12

AlxRd


2 Answers

Specify the axis.lty, names.arg and mgp inside the barplot function in the loop and you ll be fine:

#I haven't changed anything else before the for-loop
#only changes have taken place inside the barplot function below
for(i in 1:9) {
  # Bar plot
  barplot(mat.s[,i], xlab = colnames(mat.s)[i], 
          names.arg= as.character(-3:3), axis.lty=1, mgp=c(3,1,0.2))
}

Output:

enter image description here

In a bit more detail:

  • names.arg will add the labels
  • axis.lty=1 will add an x-axis
  • mgp is a vector of length three that controls the margins of the title, the labels and the axis line in this order. I only needed to change the third element of that to 0.2 so that the axis looks nice (check ?par).
like image 150
LyzandeR Avatar answered Feb 13 '23 02:02

LyzandeR


An alternative to LyzandeR's excellent answer is to add axis() after assigning the barplot() call to an object:

for(i in 1:9) {

  # Bar plot
  temp <- barplot(mat.s[,i],

  # X-label
  xlab = colnames(mat.s)[i])
  axis(1,at=temp,labels=-3:3)
}

enter image description here

like image 27
Sam Dickson Avatar answered Feb 13 '23 04:02

Sam Dickson