Search code examples
rggplot2

How to include all values of x from, say, 1 to 56, even if there is no datapoint for each number?


Here is the dataframe:

v'' J'' theor_freq exp_freq   delta
3   121   12540.05 12540.05 -0.0061
3   123   12514.11 12514.10 -0.0070
4   121   12453.72 12453.72 -0.0041
4   123   12427.90 12427.90 -0.0047
5   121   12368.11 12368.10 -0.0059
5   123   12342.41 12342.40 -0.0033

I'd like to graph delta across all v'' from 0 to 56, and would like to have ticks for every second v''. Here is my code:

p <- ggplot(data = df, aes(x = factor(`v''`), y = as.numeric(delta), 
colour = factor(`J''`))) +
geom_point(size = 3) +
geom_line() +
geom_hline(yintercept = 0) +
xlab("v''") +
ylab("exp-theor")+
ggtitle("Before processing")+
labs(colour = "J''")+
scale_color_manual(values = c("121" = "black", "123" = "grey"))+
theme_bw()

And here is a snippet of the graph: enter image description here

I've tried to use functions scale_x_continuous, xlim, scale_x_discrete and none of the options worked like I needed to.


Solution

  • Use scale_x_discrete(drop = FALSE) whereby you do not drop the missing levels: But first you do have to define the levels within your aesthetic for x.

    ggplot(data = df, aes(x = factor(`v''`, 0:56), y = as.numeric(delta), 
                          colour = factor(`J''`))) + # CHANGE THIS
      geom_point(size = 3) +
      geom_line() +
      geom_hline(yintercept = 0) +
      xlab("v''") +
      ylab("exp-theor")+
      ggtitle("Before processing")+
      labs(colour = "J''")+
      scale_x_discrete(drop=FALSE) + # ADD THIS CODE
      scale_color_manual(values = c("121" = "black", "123" = "grey"))+
      theme_bw()
    

    enter image description here