巧妙地向线条添加标签

Add labels to lines plotly

我需要一些帮助来标记 plotly 中的一些重叠线。

我有一个包含以下列的数据框:

df$date = c("2014-09-30","2016-03-31","2016-03-31")

df$company = c("google", "amazon", "twitter", "twitter", "amazon", "google")

df$value = c(50, 60, 40, 50, 40, 60)

所有列的大小都相同。

我正在使用按公司分组的 plotly 绘制时间序列图,所以我将有 3 条不同的线,一条用于 google,一条用于 twitter,一条用于 amazon,但我无法弄清楚如何绘制每条用图例进行颜色编码的线。我的情节代码如下:

num <- df %>% filter(Metric == "value")
num$Date <- as.Date(num$Date)
new.df <- num %>% group_by(company)
plot_ly(data=new.df) %>% add_lines(x=new.df$Date, y = new.df$value)

谢谢!

编辑:

我也试过了

df %>% filter(Metric == "value") %>% group_by("company") %>% 
  plot_ly(df) %>% add_lines(x = df$Date, y = df$Value)

无济于事。

library(ggplot2)
library(plotly)
#> 
#> Attaching package: 'plotly'
#> The following object is masked from 'package:ggplot2':
#> 
#>     last_plot
#> The following object is masked from 'package:stats':
#> 
#>     filter
#> The following object is masked from 'package:graphics':
#> 
#>     layout

# create example data
data <-
  iris %>%
  transmute(
    company = Species,
    date = seq(50) %>% as.Date(origin = "2014-09-30") %>% rep(3),
    value = Sepal.Width
  )
data
#>        company       date value
#> 1       setosa 2014-10-01   3.5
#> 2       setosa 2014-10-02   3.0
#> 3       setosa 2014-10-03   3.2
#> 4       setosa 2014-10-04   3.1
#> 5       setosa 2014-10-05   3.6

plt <-
  data %>%
  ggplot(aes(x = date, y = value, color = company)) +
  geom_line()

ggplotly(plt)

reprex package (v2.0.0)

于 2022-02-18 创建