rggforce

How to smooth the colour of paths in geom_link?


I'm trying to plot some segments between two points using geom_link from the ggforce package. I've tried following the documentation, but the colour of my paths come out jagged and are not smooth. I'm hoping someone can help me with my code so I can smooth these out. An example is below.

library(tidyverse)
library(ggforce)

dat <- data.frame(
  team = paste("Team", LETTERS[1:10]),
  x1 = runif(10, -0.2, 0.3),
  x2 = runif(10, -0.2, 0.3),
  y1 = runif(10, -0.2, 0.3),
  y2 = runif(10, -0.2, 0.3),
  col = c("#690014", "#03244d", "#004834", "#001E4C", "#000000", "#c41230",
          "#CC0000","#000000", "#005DAA", "#00274c")
)

ggplot(dat) +
  geom_link(aes(x = x1, xend = x2, y = y1, yend = y2, colour = col,
                alpha = stat(index), size = stat(index)), show.legend = FALSE) +
  scale_colour_identity()

Solution

  • Your code is fine (indeed, it matches the documentation more or less exactly).

    The issue appears to be the graphics device being used to display or save the plot. If you're using a recent version of RStudio for your analysis, you can change your graphics device to AGG in the settings: Global Options -> General -> Graphics -> Backend.

    It should render fine now including when saving.

    If you don't use RStudio or don't want to change the setting, you could use the RAGG package directly:

    library(tidyverse)
    library(ggforce)
    library(ragg)
    
    dat <- data.frame(
      team = paste("Team", LETTERS[1:10]),
      x1 = runif(10, -0.2, 0.3),
      x2 = runif(10, -0.2, 0.3),
      y1 = runif(10, -0.2, 0.3),
      y2 = runif(10, -0.2, 0.3),
      col = c("#690014", "#03244d", "#004834", "#001E4C", "#000000", "#c41230",
              "#CC0000","#000000", "#005DAA", "#00274c")
    )
    
    agg_png("example_agg_plot.png", width = 1000, height = 500, res = 144)
    ggplot(dat) +
      geom_link(aes(x = x1, xend = x2, y = y1, yend = y2, colour = col,
                    alpha = stat(index), size = stat(index)), show.legend = FALSE) +
      scale_colour_identity()
    invisible(dev.off())