3

I have some data I want to put in the plot, where xaxis is of discrete type (alphabetically ordered). I have some breaks in my data causing value not appearing in the plot (some xaxis points are not appearing at all).

I would like to add these lacking xaxis values. For example, I have such data and a plot:

df <-
  data.frame(x = rep(c("a", "b", "d", "e"), 2),
             group = c("A", "A", "A", "A", "B", "B", "B", "B"),
             value = rnorm(8))

library(ggplot2)
ggplot(df, aes(x, value, group = group, colour = group)) + 
geom_line()  

enter image description here

But I would like to add "c" value to the x axis and get something like:

enter image description here

Marta Karas
  • 4,967
  • 10
  • 47
  • 77
  • `+ scale_x_discrete(limits = letters[1:5])` ? – David Arenburg Jul 28 '14 at 09:35
  • 1
    This would be a good solution if I agree to have values from `b` to `d` joined over `c`. But I do not want to have it this way (please note the second picture! :>). – Marta Karas Jul 28 '14 at 09:37
  • A quick & dirty solution would prly be to add NA values for each group of x = "c". – lukeA Jul 28 '14 at 09:47
  • possible duplicate of [Line break when no data in ggplot2](http://stackoverflow.com/questions/14821064/line-break-when-no-data-in-ggplot2) – Henrik Jul 28 '14 at 09:48

2 Answers2

2

You can add new data using %+%. See below for an example:

# Your previous plot
p <- ggplot(df, aes(x, value, group = group, colour = group)) + 
  scale_x_discrete(limits = letters[1:5]) +
  geom_line()
# Adding new data (with value NA) and a point
p %+% rbind(df, data.frame(x="c", value=NA_real_, group=c("A", "B"))) +
  geom_point(data=data.frame(x="c", value=-1, group=NA)) 
shadow
  • 21,823
  • 4
  • 63
  • 77
  • Yep! This is my case (after excluding the last `+ geom_point(data=data.frame(x="c", value=-1, group=NA))` fragment). Big thank you! :) – Marta Karas Jul 28 '14 at 09:50
1

Expanding @DavidArenburg's idea:

ggplot(df, aes(x, value, group = paste(group, x %in% c("a", "b")), colour = group)) + 
  geom_line()  +
  scale_x_discrete(limits = letters[1:5])
Roland
  • 127,288
  • 10
  • 191
  • 288
  • I don't clearly understand what is done here. In particular, is this solution flexible to fill more than one missing xaxis points, e.g. not subsequent ones? – Marta Karas Jul 28 '14 at 10:48
  • I simply create smaller groups. Of course, you can do this with more than 2 groups that you want to combine with your original group. Simply substitute `x %in% c("a", "b")` with any other grouping you desire. – Roland Jul 28 '14 at 10:52