R:ggplot中的工具提示

R:ggplot中的工具提示,r,ggplot2,shiny,tooltip,R,Ggplot2,Shiny,Tooltip,当我将鼠标悬停在图形中的某个点上时,我希望显示高度或重量的值。我已经尝试使用plotly包和示例来实现这一点。但是我犯了各种各样的错误,我不知道如何让它工作 我已经包括了我的全部代码,所以我希望有人能帮助我解决这个问题 library("shiny") library("ggplot2") library('readxl') library('gridExtra') ui<- fluidPage( titlePanel("Animals"), sidebarLayout(

当我将鼠标悬停在图形中的某个点上时,我希望显示高度或重量的值。我已经尝试使用
plotly
包和示例来实现这一点。但是我犯了各种各样的错误,我不知道如何让它工作

我已经包括了我的全部代码,所以我希望有人能帮助我解决这个问题

library("shiny")
library("ggplot2")
library('readxl')
library('gridExtra')

ui<- fluidPage(
   titlePanel("Animals"),
   sidebarLayout(
     sidebarPanel(
  helpText("Create graph of height and/or weight animals"),
  selectInput("location", 
              label = "Choose a location",
              choices = list("New York"="New York", "Philadelphia" = "Philadelphia"),
              selected = "New York"),
  uiOutput("animal"),
  checkboxGroupInput("opti", 
              label = "Option",
              choices = c("weight", "height"),
              selected = "weight")
  ),
mainPanel(plotOutput("graph"))
))

server <- function(input, output){
  animal <- read_excel('data/animals.xlsx', sheet =1)
  var <- reactive({
    switch(input$location,
       "New York" = list("Cat1", "Dog2"),
       "Philadelphia"= list("Cat4","Dog3"))
     })

  output$animal <- renderUI({
  checkboxGroupInput("anim", "Choose an animal",
                   var())
  })

output$graph <- renderPlot({
  if (length(input$anim)==1){
    p <- ggplot(subset(animal, Name %in% input$anim & Location %in% input$location), aes(x=date))
    if ("weight" %in% input$opti){
      p <- p + geom_line(aes(y=weight)) + geom_point(aes(y=weight))
    }
    if ("height" %in% input$opti){
      p <- p + geom_line(aes(y=height)) + geom_point(aes(y=height))
    }
    print(p)
  }

  if (length(input$anim)==2){
    p1 <- ggplot(subset(animal, Name %in% input$anim[1] & Location %in% input$location), aes(x=date))
    p2 <- ggplot(subset(animal, Name %in% input$anim[2] & Location %in% input$location), aes(x=date))
    if ("weight" %in% input$opti){
      p1 <- p1 + geom_line(aes(y=weight)) + geom_point(aes(y=weight))
      p2 <- p2 + geom_line(aes(y=weight)) + geom_point(aes(y=weight))
    }
    if ("height" %in% input$opti){
      p1 <- p1 + geom_line(aes(y=height)) + geom_point(aes(y=height))
      p2 <- p2 + geom_line(aes(y=height)) + geom_point(aes(y=height))
    }
    grid.arrange(p1,p2, ncol = 2)
  }
})
}
shinyApp(ui=ui, server= server)
我使用了工具提示并对其进行了一点定制

您的绘图最初不会显示,因为您没有返回任何绘图。我返回一个ggplot对象
p
,而不调用
print
函数

通常,我对您的代码进行了大量修改,结果如下:

由于函数
nearPoints
需要传递给ggplot的相同数据集,因此我必须创建一个新的
reactive
,在其中我对数据进行了一些子集设置和重塑

而不是
grid.arrange
创建两个独立的图,我使用
facet\u grid
(因此我必须转换数据)。我还用颜色来区分线条

使用您提供的示例数据,一切正常


完整示例:

rm(ui)
rm(server)

library("shiny")
library("ggplot2")
library('readxl')
library('gridExtra')
library(reshape) # for "melt"

ui<- fluidPage(
  titlePanel("Animals"),
  sidebarLayout(
    sidebarPanel(
      helpText("Create graph of height and/or weight animals"),
      selectInput("location", 
                  label = "Choose a location",
                  choices = list("New York"="New York", "Philadelphia" = "Philadelphia"),
                  selected = "New York"),
      uiOutput("animal"),
      checkboxGroupInput("opti", 
                         label = "Option",
                         choices = c("weight", "height"),
                         selected = "weight")
    ),
    mainPanel(

      # this is an extra div used ONLY to create positioned ancestor for tooltip
      # we don't change its position
      div(
        style = "position:relative",
        plotOutput("graph", 
                   hover = hoverOpts("plot_hover", delay = 100, delayType = "debounce")),
        uiOutput("hover_info")
      )

    )
  ))

server <- function(input, output){

  animal <- read_excel('data/animals.xlsx', sheet =1)
  #animal <- read_excel("~/Downloads/test2.xlsx")
  var <- reactive({
    switch(input$location,
           "New York" = c("Cat1", "Dog2"),
           "Philadelphia"= c("Cat4","Dog3"))
  })

  output$animal <- renderUI({
    checkboxGroupInput("anim", "Choose an animal",
                       var())
  })


  output$graph <- renderPlot({
    req(input$anim, sub())

    if (length(input$anim) == 1) {
      p <- ggplot(sub(), aes(x = date, colour = variable))
      p <- p + geom_line(aes(y = value)) + 
               geom_point(aes(y = value)) +
        guides(colour = guide_legend(title = NULL))

      return(p) # you have to return the plot
    }

    if (length(input$anim) == 2) {

      p <- ggplot(sub(), aes(x = date, colour = variable)) +
        geom_line(aes(y = value)) + 
        geom_point(aes(y = value)) + 
        facet_grid(~ Name) + 
        guides(colour = guide_legend(title = NULL))

      return(p) # you have to return the plot
    }
  })

  observe({
    print(sub())
  })


  sub <- reactive({
    req(input$anim)

    if (length(input$anim) == 1) {

      df <- animal[animal$Name %in% input$anim & animal$Location %in% input$location, ]
      df <- melt(as.data.frame(df), measure.vars = c("weight", "height"))
      df <- subset(df, df$variable %in% input$opti)
      return(df)
    }

    if (length(input$anim) == 2) {
      df <- animal[animal$Name %in% input$anim & animal$Location %in% input$location, ]
      df$Name <- factor(df$Name)
      df <- melt(as.data.frame(df), measure.vars = c("weight", "height"))
      df <- subset(df, df$variable %in% input$opti)
      return(df)
    }
  })

  output$hover_info <- renderUI({
    hover <- input$plot_hover
    point <- nearPoints(sub(), hover, threshold = 5, maxpoints = 1, addDist = TRUE)

    if (nrow(point) == 0) return(NULL)

    left_pct <- (hover$x - hover$domain$left) / (hover$domain$right - hover$domain$left)
    top_pct <- (hover$domain$top - hover$y) / (hover$domain$top - hover$domain$bottom)

    left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left)
    top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top)

    style <- paste0("position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); ",
                    "left:", left_px + 2, "px; top:", top_px + 2, "px;")

    wellPanel(
      style = style,
      p(HTML(paste0("<b>", point$variable, ": </b>", point$value)))
    )
  })


}
shinyApp(ui = ui, server = server)
rm(用户界面)
rm(服务器)
图书馆(“闪亮”)
图书馆(“ggplot2”)
库('readxl')
库('gridExtra')
库(重塑)#用于“熔化”
ui我使用了工具提示并对其进行了一些定制

您的绘图最初不会显示,因为您没有返回任何绘图。我返回一个ggplot对象
p
,而不调用
print
函数

通常,我对您的代码进行了大量修改,结果如下:

由于函数
nearPoints
需要传递给ggplot的相同数据集,因此我必须创建一个新的
reactive
,在其中我对数据进行了一些子集设置和重塑

而不是
grid.arrange
创建两个独立的图,我使用
facet\u grid
(因此我必须转换数据)。我还用颜色来区分线条

使用您提供的示例数据,一切正常


完整示例:

rm(ui)
rm(server)

library("shiny")
library("ggplot2")
library('readxl')
library('gridExtra')
library(reshape) # for "melt"

ui<- fluidPage(
  titlePanel("Animals"),
  sidebarLayout(
    sidebarPanel(
      helpText("Create graph of height and/or weight animals"),
      selectInput("location", 
                  label = "Choose a location",
                  choices = list("New York"="New York", "Philadelphia" = "Philadelphia"),
                  selected = "New York"),
      uiOutput("animal"),
      checkboxGroupInput("opti", 
                         label = "Option",
                         choices = c("weight", "height"),
                         selected = "weight")
    ),
    mainPanel(

      # this is an extra div used ONLY to create positioned ancestor for tooltip
      # we don't change its position
      div(
        style = "position:relative",
        plotOutput("graph", 
                   hover = hoverOpts("plot_hover", delay = 100, delayType = "debounce")),
        uiOutput("hover_info")
      )

    )
  ))

server <- function(input, output){

  animal <- read_excel('data/animals.xlsx', sheet =1)
  #animal <- read_excel("~/Downloads/test2.xlsx")
  var <- reactive({
    switch(input$location,
           "New York" = c("Cat1", "Dog2"),
           "Philadelphia"= c("Cat4","Dog3"))
  })

  output$animal <- renderUI({
    checkboxGroupInput("anim", "Choose an animal",
                       var())
  })


  output$graph <- renderPlot({
    req(input$anim, sub())

    if (length(input$anim) == 1) {
      p <- ggplot(sub(), aes(x = date, colour = variable))
      p <- p + geom_line(aes(y = value)) + 
               geom_point(aes(y = value)) +
        guides(colour = guide_legend(title = NULL))

      return(p) # you have to return the plot
    }

    if (length(input$anim) == 2) {

      p <- ggplot(sub(), aes(x = date, colour = variable)) +
        geom_line(aes(y = value)) + 
        geom_point(aes(y = value)) + 
        facet_grid(~ Name) + 
        guides(colour = guide_legend(title = NULL))

      return(p) # you have to return the plot
    }
  })

  observe({
    print(sub())
  })


  sub <- reactive({
    req(input$anim)

    if (length(input$anim) == 1) {

      df <- animal[animal$Name %in% input$anim & animal$Location %in% input$location, ]
      df <- melt(as.data.frame(df), measure.vars = c("weight", "height"))
      df <- subset(df, df$variable %in% input$opti)
      return(df)
    }

    if (length(input$anim) == 2) {
      df <- animal[animal$Name %in% input$anim & animal$Location %in% input$location, ]
      df$Name <- factor(df$Name)
      df <- melt(as.data.frame(df), measure.vars = c("weight", "height"))
      df <- subset(df, df$variable %in% input$opti)
      return(df)
    }
  })

  output$hover_info <- renderUI({
    hover <- input$plot_hover
    point <- nearPoints(sub(), hover, threshold = 5, maxpoints = 1, addDist = TRUE)

    if (nrow(point) == 0) return(NULL)

    left_pct <- (hover$x - hover$domain$left) / (hover$domain$right - hover$domain$left)
    top_pct <- (hover$domain$top - hover$y) / (hover$domain$top - hover$domain$bottom)

    left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left)
    top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top)

    style <- paste0("position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); ",
                    "left:", left_px + 2, "px; top:", top_px + 2, "px;")

    wellPanel(
      style = style,
      p(HTML(paste0("<b>", point$variable, ": </b>", point$value)))
    )
  })


}
shinyApp(ui = ui, server = server)
rm(用户界面)
rm(服务器)
图书馆(“闪亮”)
图书馆(“ggplot2”)
库('readxl')
库('gridExtra')
库(重塑)#用于“熔化”

ui您还应该使用dput函数提供示例数据我不知道dput函数是什么,但我将数据添加到了@unnameUsers代码中您还应该使用dput函数提供示例数据我不知道dput函数是什么,但我将数据添加到了@unnameUsers代码中谢谢,代码工作起来很有魅力!我不完全理解它是如何工作的,但我很高兴它是:)我知道你已经帮了我很多。但是你可能知道如何更改工具提示显示的小数位数吗?在wellPanel中,将point$value包装为“round”,如下所示:round(point$value,3),其中3是小数位数。你重新安装了软件包,现在工具提示正常工作了吗?非常感谢,我尝试使用HTML代码执行此操作,但找不到任何有效的方法。有时候答案比我想象的要简单。是的,一切都很完美谢谢你,代码工作起来很有魅力!我不完全理解它是如何工作的,但我很高兴它是:)我知道你已经帮了我很多。但是你可能知道如何更改工具提示显示的小数位数吗?在wellPanel中,将point$value包装为“round”,如下所示:round(point$value,3),其中3是小数位数。你重新安装了软件包,现在工具提示正常工作了吗?非常感谢,我尝试使用HTML代码执行此操作,但找不到任何有效的方法。有时候答案比我想象的要简单。是的,一切都很完美