r - 使用 R 中的plot_ly 单独更改图例

标签 r plotly

我在 R 中使用 plot_ly,并尝试创建下面这个简单的图表。我尝试指出观察 2011 年之前的年份并预测 >= 2011 年的年份。问题始终是传说

  1. 第一个图:几乎是我想要的,但我无法删除“trace 4”图例条目。
  2. 第二个 plotly :我无法删除由“what”触发的图例

有人能解决这个问题吗?

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

enter image description here enter image description here

关于r - 使用 R 中的plot_ly 单独更改图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49978330/

相关文章:

r - 显示一年一次并在其中分组月份的简洁方法?

rworldmap软件包国家列表

python - Plotly - 在 Density Mapbox 上添加 Scatter Geo 点和轨迹

r - 使用 plotly 向现有散点图添加点

R - plotly - 结合气泡图和等值线图

r - 使用 dplyr 和 mutate 对多列中的每一列使用单独的条件

r - 将 Rcurl 与 HTTP 一起使用

r - 将字符串的不同列模式组合到 R 中的新列

R Plotly 动画 - 初始帧

javascript - plotly 更新数据