在图中分组数据的黄土不能正常工作

时间:2017-11-14 10:01:47

标签: r plotly

我想用图表中的分组数据创建黄土图。它无法正常工作,因为它只生成一行。这似乎是一个错误。

df <- data.frame(
         id  = rep(1:1000, 3),
         value = c(rnorm(1000,mean = 2), 
                   rnorm(1000,mean = 4), 
                   rnorm(1000,mean = 6)),
         var = rep(LETTERS[1:3], each = 1000))

# ggplot2 - it works as it should be
ggplot(df, aes(id, value, color  = var)) +
  geom_smooth(method = "loess")

# plotly - it doesn't work properly
df %>%
  plot_ly(x = ~id) %>%
  add_markers( y = ~value, color = ~var) %>%
  add_lines(y = ~fitted(loess(value ~ id)), color = ~var)

1 个答案:

答案 0 :(得分:3)

这是预期的行为,因为您未在add_lines电话中按组调整黄土。

这是一种首先按组计算拟合然后绘制

的方法
library(tidyverse)
library(plotly)

df %>% 
  group_by(var) %>%
  mutate(fit = fitted(loess(value ~ id))) %>%
  plot_ly(x = ~id) %>%
  add_markers( y = ~value, color = ~var, alpha = 0.5) %>%
  add_lines(y = ~fit, color = ~var)

enter image description here