rggplot2

Avoid gaps when using geom_path() with colour bin values that are factors


I'm trying to plot lines using geom_path() and hex values for colour. When I use numeric data for assigning colour (bins) the plotting is continuous. However, if the colour vars are factors (bins1), gaps appear between each colour.

library(ggplot2)

df <- structure(list(x = c(0, 0.57, 0.43, -0.65, -2.27, -3.5, -3.39, 
-1.5, 1.75, 5.12, 7.01, 6.21, 2.55, -2.87, -7.97, -10.51, -9.02, 
-3.59, 4, 10.84, 14.01), y = c(0, 0.41, 1.33, 2, 1.64, -0.01, 
-2.48, -4.67, -5.32, -3.68, 0.03, 4.56, 8.01, 8.64, 5.71, -0.07, 
-6.66, -11.36, -11.96, -7.73, 0.13), bins = c(1L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L), bins1 = c("#e2c207", "#e2c207", "#e2c207", "#e2c207", "#e2c207", 
"#e2c207", "#e2c207", "#ff6915", "#ff6915", "#ff6915", "#ff6915", 
"#ff6915", "#ff6915", "#ff6915", "#8b0d0d", "#8b0d0d", "#8b0d0d", 
"#8b0d0d", "#8b0d0d", "#8b0d0d", "#8b0d0d")), row.names = c(NA, 
21L), class = "data.frame")

ggplot(df, aes(x, y)) + 
  geom_path(aes(colour = bins1)) +
  scale_colour_identity() +
  coord_fixed() +
  theme_void()

1

I tried this option also but the problem persisted:

colours <- c("#e2c207", "#ff6915", "#8b0d0d")

ggplot(df, aes(x, y, colour = I(colours[bins]))) + 
  geom_path() +
  coord_fixed() +
  theme_void()

Solution

  • Using dplyr and tidyr, you can:

    1. add a row to each bin group
    2. lag or lead the preceding or following xy values
    library(dplyr)
    library(tidyr)
    library(ggplot2)
    
    # Lag colour value
    df |>
      group_by(bins, bins1) |>
      group_modify(~ add_row(.x, .before = 0)) |>
      ungroup() |>
      slice(-1) |>
      fill(x, y, .direction = "down") |>
      ggplot(aes(x, y, colour = bins1)) + 
      geom_path() +
      scale_colour_identity() +
      coord_fixed() +
      theme_void()
    

    2

    # Lead colour value
    df |>
      group_by(bins, bins1) |>
      group_modify(~ add_row(.x, .after = nrow(.x))) |>
      ungroup() |>
      slice(-n()) |>
      fill(x, y, .direction = "up") |>
      ggplot(aes(x, y, colour = bins1)) + 
      geom_path() +
      scale_colour_identity() +
      coord_fixed() +
      theme_void()
    

    3