2016-12-09 120 views
0

有没有办法在ggplot中定义自己的线型? 在线图中,我希望线条显示为小数字。有点像线型“点”,只有很少的“1”或“2”而不是点。 我试过用标签,但它们只显示在定义的点上,而不是在两者之间的空格中。我无法弄清楚,如何落实到scale_linetype_manual有没有办法在ggplot中使用自定义线型

df <- data.frame(
    x = runif(10), 
    y = runif(10), 
    z = c(1,1,1,1,1,2,2,2,2,2)) 

ggplot(df, aes(x, y)) + 
    geom_line(aes(colour=as.factor(z), linetype = as.factor(z)))+ 
    geom_text(aes(label=z)) 
+1

你最有可能可以't使用带'linetype'的'geom_line'来做到这一点。你可以插入更多的值并使用'geom_text'。 – Axeman

回答

1

你可以试着适应this strategy分裂路径成等间隔段,

enter image description here

set.seed(123) 
df <- data.frame(
    x = runif(10), 
    y = runif(10), 
    z = c(1,1,1,1,1,2,2,2,2,2)) 

parametric_smoothie <- function(x, y, sort = TRUE, N=1e2, phase=1, offset=0) { 

    if(sort){ 
    ox <- order(x) 
    x <- x[ox] 
    y <- y[ox] 
    } 

    lengths <- c(0, sqrt(diff(x)^2 + diff(y)^2)) 
    l <- cumsum(lengths) 
    lmax <- max(l) 
    newpos <- seq(phase*lmax/N, lmax-phase*lmax/N, length.out = N) + offset*lmax/N 
    xx <- approx(l, x, newpos)$y 
    yy <- approx(l, y, newpos)$y 

    ## new points, equi-spaced 
    dnew <- data.frame(x = xx, y = yy) 

    xx <- c(x, xx) 
    yy <- c(y, yy) 
    ox <- order(xx) 
    xx <- xx[ox] 
    yy <- yy[ox] 

    ## original and new points combined 
    dcomb <- data.frame(x = xx, y = yy) 

    list(dnew = dnew, dcomb = dcomb) 
} 

dl <- plyr::dlply(df, "z", function(.d) parametric_smoothie(.d$x, .d$y, N=10)) 

df2 <- plyr::ldply(dl, "[[", "dnew") 
df3 <- plyr::ldply(dl, "[[", "dcomb") 

ggplot(df, aes(x, y)) + 
    geom_line(data = df3, aes(colour=as.factor(z))) + 
    geom_point(data = df2, colour = "grey92", size=5) + 
    geom_point(aes(colour=as.factor(z))) + 
    geom_text(data = df2, aes(label=z), size=3) 
+0

谢谢!它很好用 – user3845433

+0

@ user3845433考虑接受/提高答案 – baptiste

相关问题