4
votes

I have the following code in server.R:

library(shiny)
library(plotly)

art.data <- read.csv("data1.csv", stringsAsFactors = FALSE)

shinyServer(function(input, output) {

output$distPlot <- renderPlotly({
    col.str <- paste0(input$colspa, ".", input$rgbchoice, ".median")
    p <- ggplot(art.data, aes(x = year, y = art.data[[col.str]], text = paste0(artist, "<br>", art))) + geom_point(size = 1) + xlab("Year") + stat_smooth(method = loess, se = FALSE)
    ggplotly(p , tooltip = "text")
})
})

If I remove tooltip then the regression line is there in output graph but with tooltip included, regression line does not appear in the graph. Any solutions to have both the things together?

With tooltip

Without tooltip in ggplotly() and text in aes()

1
Please add data1.csv or some sample data to get a reproducible example.Maximilian Peters
Have you tried plotly package?Rahul Agarwal
@RahulAgarwal I tried but nothing worked. The solution presented below works perfectly.Charles

1 Answers

3
votes

The aesthetic text needs the aesthetic group.
Let start considering this example:

art.data <- data.frame(year=1430:1490, y=rnorm(61), 
            artist=sample(LETTERS,61, replace=T), art=sample(letters,61, replace=T))
col.str <- 2

library(ggplot2)
ggplot(art.data, aes(x = year, y = art.data[[col.str]], 
                     text=paste0(artist, "<br>", art))) + 
    geom_point(size = 1) + 
    stat_smooth(method = loess, se = FALSE) +
    xlab("Year") 

In this case the loess line is not plotted on the graph:

enter image description here

Adding group=1 in the ggplot aesthetics solves the problem:

p <- ggplot(art.data, aes(x = year, y = art.data[[col.str]], 
                     text=paste0(artist, "<br>", art), group=1)) + 
    geom_point(size = 1) + 
    stat_smooth(method = loess, se = FALSE) +
    xlab("Year") 
p

enter image description here

and ggplotly now works nicely:

library(plotly)
ggplotly(p, tooltip="text")

enter image description here