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:
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?
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))
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"))
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 andbeside
isTRUE
,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 toc(0,1)
if height is a matrix and beside isTRUE
, and to0.2
otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With