简体   繁体   English

如何在 R 中使用 Plotly 在折线图上仅显示一些悬停信息点

[英]How to show only some hoverinfo points on a line graph with Plotly in R

I have traffic and article dfs as follows:我的流量和文章dfs如下:

library(plotly)
library(dplyr)

set.seed(101)
traffic <- data.frame(Date = seq(as.Date("2021-06-01"), as.Date("2021-07-10"), by="days"),
                      Views = round(rnorm(40, 5000, 200),0))

articleData <- data.frame(Date = as.Date(c("2021-06-01", "2021-07-04", "2021-07-10")),
                          article = c("Article 1", "Article 2", "Article 3"))

joinedData <- left_join(traffic, articleData)

I want to make a plotly line graph that shows a line for traffic, but for the 3 dates where there were articles published I would like to add a dot that the person can cover over and it will show what article was published that day.我想制作一个 plotly 折线图,显示一条流量线,但是对于发表文章的 3 个日期,我想添加一个人可以覆盖的点,它将显示当天发表的文章。 Below is what I was able to put together:以下是我能够汇总的内容:

plot_ly(data = joinedData, x = ~Date, y = ~Views, type = "scatter", mode = "lines") %>%
  add_trace(hoverinfo = "text", text = ~article, mode = "markers")

This technically works, but it puts a marker on every single day, not just the 3 days that had articles.这在技术上是有效的,但它在每一天都做了一个标记,而不仅仅是有文章的 3 天。 Is there a way to ignore marking the days that don't have articles?有没有办法忽略标记没有文章的日子? I really just want to draw attention to the days that have articles published and show whether that article shows a spike in traffic or not.我真的只想提请注意发表文章的日子,并说明该文章是否显示流量激增。

I think you were really close in your question.我认为您的问题非常接近。 I think you just need to filter your data for those three articles and create a new dataframe.我认为您只需要过滤这三篇文章的数据并创建一个新的 dataframe。 You can use the new dataset in add_trace.您可以在 add_trace 中使用新数据集。 This will only put points on the dates that had articles published.这只会在发表文章的日期上加分。

library(dplyr)
library(plotly)
filteredJoinedData <- joinedData %>%
  filter(article != "NA")

plot_ly(data = joinedData, x = ~Date, y = ~Views, type = "scatter", mode = "lines") %>%
  add_trace(data = filteredJoinedData, hoverinfo = "text", text = ~article, mode = "markers")

Giving you this graph给你这张图

例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM