1

How to add dummy values on x-axis in ggplot2

I have 0,2,4,6,12,14,18,22,26 in data and that i have plotted on x-axis. Is there a way to add the remaining even numbers for which there is no data in table? this will create due spaces on the x-axis.

after the activity the x-axis should show 0,2,4,6,8,10,12,14,16,18,20,22,24,26

i have tried using rbind.fill already to add dummy data but when I make them factor the 8,10,12etc coming in last

Thanks

enter image description here

Sana Ali
  • 165
  • 1
  • 11
  • Is your variable that you use for the x axis a factor or numeric? if it is a factor you could use `as.numeric()` in your ggplot function where you set x, then you should be able to have the x axis spaced correctly. – Sarina May 02 '17 at 09:05

1 Answers1

1

Hope this make sense:

library(ggplot2)

gvals <- factor(letters[1:3])
xvals <- factor(c(0,2,4,6,12,14,18,22,26), levels = seq(0, 26, by = 2))
yvals <- rnorm(10000, mean = 2)

df <- data.frame(x = sample(xvals, size = length(yvals), replace = TRUE),
                 y = yvals,
                 group = sample(gvals, size = length(yvals), replace = TRUE))

ggplot(df, aes(x = x, y = y)) + geom_boxplot(aes(fill = group)) +
    scale_x_discrete(drop = FALSE)

The tricks are to make the x-variable with all levels you need and to specify drop = FALSE in scale.

kristang
  • 557
  • 5
  • 17
amatsuo_net
  • 2,409
  • 11
  • 20