1
votes

Is there a way to add a line for specific factor levels in ggplot? this simple example could provide a base to explain what I'm trying to say. In this case I'd like to avoid plotting the last level.

ggplot(BOD, aes(x=factor(Time), y=demand, group=1)) + geom_line() + geom_point()

enter image description here

1
Hi Juanchi, it would help if you include a small example of the data you are working with in a format that is easy to copy-and-paste into R. - Keith Hughitt
Please provide BOD (use dput(BOD)). Your expected output is not clear : your just want to remove the 7 from the x scale? Or remove the last point? - scoa
BOD is in the R base... it is not needed to include as dput() - Juanchi
I only want to remove the line, not the level from the axis... - Juanchi

1 Answers

2
votes

You can just simply create a new variable with an NA-value for Time == 7:

BOD$demand2[BOD$Time<7] <- BOD$demand[BOD$Time<7]

and then plot:

ggplot(BOD, aes(x=factor(Time), y=demand2, group=1)) + 
  geom_line() + 
  geom_point() +
  theme_classic()

You could also do it on the fly by utilizing the functionality of the data.table-package:

library(data.table)
ggplot(data = as.data.table(BOD)[Time==7, demand := NA],
       aes(x=factor(Time), y=demand, group=1)) + 
  geom_line() + 
  geom_point() +
  theme_classic()

To answer your comment, you could include the point at 7 as follows:

ggplot(BOD, aes(x=factor(Time), y=demand2, group=1)) + 
  geom_line() + 
  geom_point(aes(x=factor(Time), y=demand)) +
  theme_classic()