Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I control space between bars?

Tags:

r

bar-chart

I am plotting bar chart using the following code:

heights1=c(5,5,4.5,4)
barplot(heights1, main="Language ", names.arg=c("Hindi R/W", "Speak" , "English 
R/W","Speak"), ylab=" level ", xlab="Language starting with mostly used",  
cex.names=0.8, col=c("darkblue","red"))

The output comes like this:

enter image description here

But What I want is that the "Hindi R/w" and "Speak" should combine without any gap, and then a space comes and then "English R/w" and "Speak" should combine. How do I do this?

like image 356
gpuguy Avatar asked Dec 18 '12 12:12

gpuguy


2 Answers

You should add argument space= to your barplot() function, where numbers correspond to space before each bar.

heights1=c(5,5,4.5,4)    
barplot(heights1, main="Language ", names.arg=c("Hindi R/W", "Speak" , "English 
  R/W","Speak"), ylab=" level ", xlab="Language starting with mostly used",  
  cex.names=0.8, col=c("darkblue","red"),space=c(0.2,0,0.2,0))

enter image description here

like image 104
Didzis Elferts Avatar answered Oct 06 '22 14:10

Didzis Elferts


Your life would be much easier if your data were properly formatted. The barplot function takes input of a vector or matrix. When the input is a matrix, R can use the dimnames to automatically label things for you.

Try this:

heights1 = c(5, 5, 4.5, 4)
barplot(t(matrix(heights1, ncol=2, byrow=TRUE, 
                 dimnames=list(c("Hindi", "English"), 
                               c("Read/Write", "Speak")))), 
        main="Language ", ylab="Level", 
        xlab="Language starting with mostly used", 
        col=c("darkblue", "red"), 
        beside=TRUE, ylim = c(0, 6), 
        legend.text = TRUE,
        args.legend = list(x = "topright")) 

enter image description here

If the spacing between the two groups is too much, then the suggestion by @Didzis is appropriate here too. Add space = c(0, .2) to your barplot command, keeping in mind the details from the documentation:

If height is a matrix and beside is TRUE, space may be specified by two numbers, where the first is the space between bars in the same group, and the second the space between the groups. If not given explicitly, it defaults to c(0,1) if height is a matrix and beside is TRUE, and to 0.2 otherwise.

like image 22
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 06 '22 15:10

A5C1D2H2I1M1N2O1R2T1