Jacob
Jacob

Reputation: 422

How to add separate data to plotly graph in R

I build monthly reports where I plot web traffic on a plotly line graph, and when I hover over the data points, it pulls up the date & page visits. I have a second graph where I have the date and the article that we posted the date. An example is below:

library(plotly)

Day <- seq.Date(as.Date("2020-08-01"),as.Date("2020-08-31"), by=1)
Visits <- round(rnorm(31, 150, 5),0)
Web_Traffic <- data.frame(Day, Visits)

Publishing_Date <- as.Date(c("2020-08-01", "2020-08-15", "2020-08-24"))
Article <- c("Article 1", "Article2", "Article3")

Blog <- data.frame(Publishing_Date, Article)

plot_ly(Web_Traffic, x=Day, y=Visits, type = "scatter", mode = "line")

Is there a way where on Aug 1, Aug 15, and Aug 24, on the line graph, when I hover over the data points, it can also include the article that was published on that day? and if this is possible, is there a way to keep the data up on the graph without needing to hover over the graph? (i.e. if I want to copy the graph to a powerpoint)

Upvotes: 1

Views: 49

Answers (1)

DaveArmstrong
DaveArmstrong

Reputation: 21802

You could do something like the following - where you mark the published articles with vertical segments:

plot_ly() %>%
  add_lines(data=Web_Traffic, x=Day, y=Visits, name="Visits" ) %>%
  add_segments(data=Blog, x=Publishing_Date, 
                          xend=Publishing_Date, 
                          y=min(Web_Traffic$Visits), 
                          yend=max(Web_Traffic$Visits), 
                          name="Published Articles")

enter image description here

Upvotes: 1

Related Questions