Gaurav Chawla
Gaurav Chawla

Reputation: 1643

How to display x-value(names) in barplot in R?

I have the following data

r<-structure(list(Relation = structure(c(3L, 4L, 1L, 2L), .Label = c("Neighbours", 
"Other known persons", "Parents/Close Family Members", "Relatives"
), class = "factor"), Number = c(539L, 2315L, 10782L, 18171L)), .Names = c("Relation", 
"Number"), class = "data.frame", row.names = c(NA, -4L))

when I plot barplot using following command:

 barplot(r[,2],names.arg=r$Relation,col="green")

The x-value names under the Relation column name is not visible/shown in the plot. What is wrong here? Thanks

Upvotes: 0

Views: 6153

Answers (2)

IRTFM
IRTFM

Reputation: 263301

Try substituting a line feed for each space in names.arg:

barplot(r[,2],names.arg=gsub("\\s","\n", r$Relation),col="green", line=2)

enter image description here

(Needed to shift the labels down with the "line" parameter.)

Upvotes: 4

jlhoward
jlhoward

Reputation: 59335

The answer to "what is wrong here" is in the comments. Here is a solution using ggplot, which does a much better job managing long names.

library(ggplot2)
ggplot(r, aes(x=Relation, y=Number)) + 
  geom_bar(stat="identity", fill="lightgreen", color="grey50")

enter image description here

When you have long names like this sometimes it's better to use horizontal bars.

ggplot(r, aes(x=Relation, y=Number)) + 
  geom_bar(stat="identity", fill="lightgreen", color="grey50")+
  coord_flip()

enter image description here

Upvotes: 4

Related Questions