sisbra
sisbra

Reputation: 1

R spaghetti plot - changing line colour with connected points

Spaghetti plot with geom_line and geom_smooth. I have to plot "f0" according to "time_steps" with the lines changing their colour according to the factor "part" without disconnecting between its two levels "os" and "fv". Also the smooth disappear when "part" changes.

The structure of my dataset:

structure(list(time_steps = 1:20, f0.2 = c(203.61, 204.62, 204.23, 
207.71, 198.5, 184.43, 185.15, 182.13, 183.2, 189.47, 188.88, 
188.43, 188.53, 189.41, 191.15, 193.76, 196.6, 199.44, 201.45, 
202.53), part = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("os", 
"fv"), class = "factor")), row.names = c(NA, -20L), class = "data.frame")

The code I wrote:

ggplot (df, aes(time_steps, f0, colour = (part))) +
  geom_line(alpha = 0.1) + geom_smooth(size = 2)

The plot I got with a disconnected line:

here

Does someone have suggestions to solve this problem?

Upvotes: 0

Views: 444

Answers (1)

Ben Norris
Ben Norris

Reputation: 5747

Breaking the line plot by color will always leave a gap unless there is a point in common between the two values of part. That gap signifies that there is no value of time_steps > 10 for part == "os" and no values of time_steps < 12 for part == "fv".

Using some simulated data that looks like yours, here is a work around. It involves using geom_line twice, once without a color aesthetic mapped so you can connect the points. Then I used stat_smooth() twice (once for the line and once for the ribbon) because it gives more control over the appearance of the plot.

df <- data.frame(time_steps = 1:20,
                 f0 = round(runif(20, 190, 210)),
                 part = c(rep("os", 10), rep("fv", 10)))

ggplot(df) +
   geom_line(aes(x = time_steps, y = f0), color = "black", size = 1.5, alpha = 0.5) +
   geom_line(aes(x = time_steps, y = f0, color = part), size = 1.5, alpha = 1) +
   stat_smooth(geom ='line', aes(x = time_steps, y = f0), color = "black", size = 1.5, linetype = 2, alpha=0.5) + 
   stat_smooth(geom = 'ribbon', aes(x = time_steps, y = f0), color = "NA", fill = "black", alpha = 0.1)

trying to plot what the OP wants

Upvotes: 1

Related Questions