'What is the easiest way to add a tooltip to a boxplot(ggplot) generated through Shiny?
I need the y-value displayed in a tooltip-style text box when the cursor hovers over a bar. I have to imagine this is a simple function through Shiny, but I haven't been able to figure it out.
I'll include the relevant UI and server code below:
UI :
#TAB 3 (QUOTA/SALES)
tabPanel(title = "Quota/Sales",
fluidRow(column(9,
wellPanel(height=600, width ="100%",
plotOutput("quota", height=550, width ="100%"
))),
column(3,
wellPanel(height=100, width ="100%",
selectInput("countyquota", "County:", choices=countychoices, selected = "Statewide"))))
)))
Server:
hdata <- reactive({
if(input$sexage == "All" & input$countyharv == "Statewide") {
harvdata}
else if(input$sexage == "All" & input$countyharv != "Statewide")
{filter(harvdata, NAME == input$countyharv)}
else if (input$sexage != "All" & input$countyharv != "Statewide")
{filter(harvdata, sexage == input$sexage, NAME == input$countyharv)}
else if (input$countyharv == "Statewide" & input$sexage != "All"){
filter(harvdata, sexage == input$sexage)
}
})
output$harv <- renderPlot({
ggplot(hdata(), aes(fill=sexage, y=harvest, x=year, label = harvest)) +
geom_bar(position="dodge", stat="identity") +
xlab("Year") +
ylab("Harvest") +
labs(fill = NULL)+
theme_bw()
})`
Solution 1:[1]
Welcome to StackOverflow. The first thing is that it is always a good idea to include a minimal reproducible example of your base code. That way you help us to help you. In your case, the code you provide does not run (is not reporducible) you have to include the data (or a sample).
Going into the answer. ggplot2 output by default does not show tooltip, you need to use a JavaScript base library for that. The more common are plotly and highcharter.
Lets create a shiny app using the mtcars dataset to show you how to take ggplot2 plots to plotly using the plotly::ggplotly() function.
Note the important comments within the code.
library(shiny)
library(plotly) # you need this packages
ui <- fluidPage(
selectInput('x', 'X axis', choices = names(mtcars), selected = 'wt'),
selectInput('y', 'Y axis', choices = names(mtcars), selected = 'mpg'),
fluidRow(
column(
width = 6,
plotOutput('static'),
),
column(
width = 6,
# New function to render plotly outputs
plotlyOutput('dynamic')
)
)
)
server <- function(input, output, session) {
# This a regular ggplot2 object.
plot <- reactive({
ggplot(
data = mtcars,
mapping = aes(x = .data[[input$x]], y = .data[[input$y]])
) +
geom_point() +
theme_bw()
})
output$static <- renderPlot({ plot() })
# 1- New render frunction to handel plotly outputs
# 2- Place a ggplot2 object within the ggplotly() function
output$dynamic <- renderPlotly({ ggplotly(plot()) })
}
shinyApp(ui, server)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Johan Rosa |

