Search code examples
rggplot2bar-chartaxis-labels

how to add x axis labels ggplot2 r


I would like to put some labels on ggplot bar plot X-axis.

data:

var.A <- as.numeric(c(1:13))
var.B <- c(4.351833, 2.938000, 4.726465, 3.747162, 3.720737, 4.297117, 4.304500, 4.061277, 4.595236, 4.105444, 3.701684, 3.523563, 4.170000)
df <- data.frame(var.A,var.B)

ggplot code:

ggplot(df, aes(x=var.A, y=var.B)) + 
  geom_bar(position=position_dodge(), stat="identity", fill="#fff68f", colour="darkgrey", width = 0.4) +
  coord_flip()+
  xlab("") +
  ylab("") +
  scale_x_discrete(labels=c("aaaaaaa aaaaa","bbbbb bbb bbbb","cccc ccc","dddd dd ddddd","eee e eeeee e ee","ffffffff","gggggggg","hhhhhhh","iiii","jjjjjj","kkkkkkk","llllll","mmmmmmmm"))

I refer to docs: ggplot documentation

How to force R to put this labels on their places on x-axxis?


Solution

  • You need to specify x as a factor. That's it.

    ggplot(df, aes(x=factor(var.A), y=var.B)) + 
      geom_bar(position=position_dodge(), stat="identity", fill="#fff68f", colour="darkgrey", width = 0.4) +
      xlab("") +
      ylab("") +
      scale_x_discrete(labels=c("aaaaaaa aaaaa","bbbbb bbb bbbb","cccc ccc","dddd dd ddddd","eee e eeeee e ee","ffffffff","gggggggg","hhhhhhh","iiii","jjjjjj","kkkkkkk","llllll","mmmmmmmm"))