我有一个“网格”结构的数据,我希望根据组变量将某些点连接在一起。 geom_line()
可以实现这一点(见下文),但我想让这些线条弯曲。怎么可以这样做? geom_curve()
似乎与此特定数据格式不兼容。谢谢。
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))
答案 0 :(得分: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)