簡體   English   中英

在 R 中使用 plot_ly 在 plotly 中單獨更改圖例

[英]Change legend individually in plotly using plot_ly in R

我在R使用plot_ly ,並嘗試在下面創建這個簡單的圖形。 我嘗試確實表明觀察到了 2011 年之前的年份,並預測了 >= 2011 年的年份。 問題始終是傳說

  1. 第一個情節:幾乎是我想要的,但我無法刪除“trace 4”圖例條目。
  2. 第二個情節:我無法刪除由“什么”觸發的圖例

有人可以解決這個問題嗎?

library(plotly)

d1 <- structure(list(year = c(2006L, 2006L, 2006L, 2007L, 2007L, 2008L, 
2008L, 2009L, 2009L, 2010L, 2010L, 2010L, 2011L, 2011L, 2012L, 
2012L, 2012L, 2013L, 2013L, 2014L, 2014L, 2015L, 2015L, 2015L
), N = c(498, 500, 3890, 418, 3465, 311, 3740, 183, 3551, 363, 
386, 3503, 368, 3577, 557, 235, 3397, 287, 3479, 484, 3601, 428, 
311, 3509), part = c("1", "3", "9", "3", "9", "3", "9", "3", 
"9", "0", "3", "9", "3", "9", "1", "3", "9", "3", "9", "3", "9", 
"0", "3", "9")), .Names = c("year", "N", "part"), row.names = c(NA, 
-24L), class = c("data.frame"))

# 1st plot
plot_ly() %>% add_trace(data = d1, x=~year, y=~N, color = ~part, mode="line") %>% 
add_segments(x = 2010.5, xend = 2010.5, y = 0, yend = max(d1$N))

d1$what <- "obs"
d1$what[d1$year <= 2010] <- "fc"

# 2nd plot
plot_ly() %>% add_trace(data = d1, x=~year, y=~N, color = ~part, mode="line", linetype=~what)

謝謝! 曼努埃爾

參數showlegend允許抑制圖例條目。

# 1st plot
plot_ly() %>% add_trace(data = d1, x=~year, y=~N, color = ~part,
              mode="line", type="scatter") %>% 
add_segments(x = 2010.5, xend = 2010.5, y = 0, yend = max(d1$N), showlegend=FALSE)


# 2nd plot
p <- plot_ly() 

for (k in unique(d1$part)) {
   p <- add_trace(p, data = subset(d1,d1$year <= 2010 & d1$part==k), 
      type="scatter", mode="lines", color=k,
      x=~year, y=~N, legendgroup=k) 
   p <- add_trace(p, data = subset(d1,d1$year > 2010 & d1$part==k), line=list(dash=4),
      type="scatter", mode="lines", color=k,
      x=~year, y=~N,  showlegend=FALSE, legendgroup=k)
}
p

在此處輸入圖片說明 在此處輸入圖片說明

暫無
暫無

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

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