Brian Fisher
Brian Fisher

Reputation: 1367

remove connecting lines when using color aesthetic ggplot in r

I'm plotting a time series with gaps from one source filled in from a second. Plotting this to indicate the source, I specify the source as a color aesthetic, but ggplot adds connecting lines tieing the gaps together.
Is there a clean way to remove these connecting lines? Ideally, I would like the separate groups to be connected, since I am using it as one data set.

library(ggplot)
set.seed(914)
df=data.frame(x=c(1:100),y=runif(100), z = rep(c("a", "b"), each = 25, times = 2))


ggplot(df, aes(x=x, y = y, color = z))+
      geom_line()

Example_with_connecting_lines

Removing connetion lines between missing Dates in ggplot suggests creating a group aesthetic, or making the gaps explicit using NA values.
I don't have any clear grouping aesthetic in my real data, like the year in the referenced example, and with many irregularly spaced gaps, it isn't immediately clear how to insert NA's in every gap.

Upvotes: 0

Views: 997

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174586

As long as your colored "groups" are sequential in your data frame (as in your example) you can do:

ggplot(df, aes(x=x, y = y, color = z,
               group = factor(c(0, cumsum(abs(head(z, -1) != tail(z, -1))))))) +
      geom_line()

enter image description here

Or, for brevity, use data.table::rleid:

ggplot(df, aes(x=x, y = y, color = z, group = data.table::rleid(z))) +
      geom_line()

which gives the same result

Upvotes: 3

Related Questions