簡體   English   中英

有沒有辦法在ggplot中使用自定義線型

[英]Is there a way to use selfdefined linetypes in ggplot

有沒有辦法在ggplot中定義自己的線型? 在折線圖中,我希望線條顯示為小數字。 有點像線型“點綴”,只帶有少量“ 1”或“ 2”而不是點。 我嘗試過使用標簽,但是它們僅顯示在定義的點上,而不顯示在它們之間的空格中。 我不知道如何將其實現為scale_linetype_manual

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))

您可以嘗試采用這種策略 ,將路徑分成等距的段,

在此處輸入圖片說明

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)  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM