0

I have a data that is of a "grid" structure and I wish to connect certain points together according to a group variable. geom_line() can achieve this (see below), but I want to get those lines to be curved. How could this be done? geom_curve() does not seem compatible with this particular data format. Thank you.

df = data.frame(
 x = factor(c(1,1,2,2)),
 y = factor(c(1,2,1,2)),
 group = c("A","A","B","B")) 

df %>% 
 ggplot(aes(x = x, y = y)) +
 geom_point() +
 geom_line(aes(group = group))
Kevin
  • 333
  • 1
  • 3
  • 9
  • Check [here](https://stackoverflow.com/questions/33290259/r-ggplot-multiple-series-curved-line) for inspiration. I haven't been able to spline your data effectively, though. – csgroen Oct 29 '17 at 12:11
  • There is `geom_xspline` from the package `GGalt` that might be what you need. – Jake Kaupp Oct 29 '17 at 13:36

1 Answers1

1
# A "toy" data set    
df1 = data.frame(
 x = factor(c(1,1,2,2,3,3)),
 y = factor(c(1,2,1,2,1,2)),
 group = c("A","A","B","B","C","C")) 

library(ggplot2)
library(dplyr)

# Create a matrix where on each row there are the coordinates 
# of the starting and ending points
# One row for each group 
df1 %>% group_by(group) %>%
mutate(X1=x[1], X2=x[1], Y1=y[1], Y2=y[2]) -> df2
( df2 <- df2[seq(1,nrow(df2),2),c("X1","X2","Y1","Y2")] )
# A tibble: 3 x 4
#      X1     X2     Y1     Y2
#  <fctr> <fctr> <fctr> <fctr>
# 1      1      1      1      2
# 2      2      2      1      2
# 3      3      3      1      2

ggplot() +
 geom_point(data=df1, aes(x=x, y=y)) +
 geom_curve(data=df2,aes(x=X1, y=Y1, xend=X2, yend=Y2), curvature=.5)

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58