如何在 ggplot2 中悬停时在工具提示上显示 y 值 [英] How do I show the y value on tooltip while hover in ggplot2

查看:19
本文介绍了如何在 ggplot2 中悬停时在工具提示上显示 y 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将鼠标放在图形中的某个点上时,我希望显示 y 值.我的情节的代码如下所示:

I want the show the y-value when I hold my mouse on a point in the graph. The code for my plot looks like this:

output$graph <- renderPlot({
  p1 <- ggplot(data, aes(x= date)) + 
  geom_line(aes(y=Height, colour = "Height"), size=1) + 
  geom_point(aes(y=Height, colour = "Height", text = paste("Weight/Height:", Height)))
  plot(p1)
})

我做了一些研究,我认为 aes 中的 text = paste("Weight/Height:", Height) 部分将确保文本出现.不幸的是什么都没有出现.有谁知道我做错了什么?

I did some research and I thought that the text = paste("Weight/Height:", Height) part in aes would make sure that the text would appear. Unfortunately nothing appears. Does anyone know what I did wrong?

推荐答案

不幸的是 ggplot 不是交互式的,但它可以通过 plotly 包.您只需要将 plotOutput 替换为 plotlyOutput,然后使用 renderPlotly 渲染绘图.

Unfortunately ggplot is not interactive but it can be easily "fixed" with plotly package. You only need to replace plotOutput with plotlyOutput and then render a plot on with renderPlotly.

示例 1:情节

library(shiny)
library(ggplot2)
library(plotly)

ui <- fluidPage(
    plotlyOutput("distPlot")
)

server <- function(input, output) {
   output$distPlot <- renderPlotly({
      ggplot(iris, aes(Sepal.Width, Petal.Width)) + 
       geom_line() + 
       geom_point()
   })
}

shinyApp(ui = ui, server = server)


示例 2:plotOutput(..., hover = "plot_hover"):

尽管如此,我们不必使用任何特殊的包来为我们的图形引入交互性.我们需要的只是我们可爱闪亮的闪亮!我们可以使用 plotOutput 选项,例如 clickhoverdblclick 来使绘图具有交互性.(在闪亮的画廊中查看更多示例)

We don't have to use any special package to introduce the interactivity to our graphs though. All we need is our lovely shiny shiny! We can just play with plotOutput options as for instance click, hover or dblclick to make the plot interactive. (See more examples in shiny gallery)

在下面的示例中,我们通过 hover = "plot_hover" 添加悬停",然后指定延迟,默认为 300 毫秒.

In the example below we add "hovering" by hover = "plot_hover" and then specify delay which is by default 300ms.

plotOutput("distPlot", hover = "plot_hover", hoverDelay = 0)

然后我们可以通过 input$plot_hover 访问值并使用函数 nearPoints 来显示靠近点的值.

We then can access values via input$plot_hover and use a function nearPoints to show values that are near the points.

ui <- fluidPage(
  selectInput("var_y", "Y-Axis", choices = names(iris)),
  plotOutput("distPlot", hover = "plot_hover", hoverDelay = 0),
  uiOutput("dynamic")

)

server <- function(input, output) {

  output$distPlot <- renderPlot({
    req(input$var_y)
    ggplot(iris, aes_string("Sepal.Width", input$var_y)) + 
      geom_point()
  })

  output$dynamic <- renderUI({
    req(input$plot_hover) 
    verbatimTextOutput("vals")
  })

  output$vals <- renderPrint({
    hover <- input$plot_hover 
    # print(str(hover)) # list
    y <- nearPoints(iris, input$plot_hover)[input$var_y]
    req(nrow(y) != 0)
    y
  })

}
shinyApp(ui = ui, server = server)

<小时>

示例 3:自定义 ggplot2 工具提示:

第二种解决方案效果很好,但是是的……我们想做得更好!是的……我们可以做得更好!(...如果我们使用一些 javaScript 但 pssssss 不要告诉任何人!).

The second solution works great but yes...we want to do it better! And yes...we can do it better! (...If we use some javaScript but pssssss don't tell anyone!).

library(shiny)
library(ggplot2)

ui <- fluidPage(

  tags$head(tags$style('
     #my_tooltip {
      position: absolute;
      width: 300px;
      z-index: 100;
      padding: 0;
     }
  ')),

  tags$script('
    $(document).ready(function() {
      // id of the plot
      $("#distPlot").mousemove(function(e) { 

        // ID of uiOutput
        $("#my_tooltip").show();         
        $("#my_tooltip").css({             
          top: (e.pageY + 5) + "px",             
          left: (e.pageX + 5) + "px"         
        });     
      });     
    });
  '),

  selectInput("var_y", "Y-Axis", choices = names(iris)),
  plotOutput("distPlot", hover = "plot_hover", hoverDelay = 0),
  uiOutput("my_tooltip")


)

server <- function(input, output) {


  output$distPlot <- renderPlot({
    req(input$var_y)
    ggplot(iris, aes_string("Sepal.Width", input$var_y)) + 
      geom_point()
  })

  output$my_tooltip <- renderUI({
    hover <- input$plot_hover 
    y <- nearPoints(iris, input$plot_hover)[input$var_y]
    req(nrow(y) != 0)
    verbatimTextOutput("vals")
  })

  output$vals <- renderPrint({
    hover <- input$plot_hover 
    y <- nearPoints(iris, input$plot_hover)[input$var_y]
    req(nrow(y) != 0)
    y
  })  
}
shinyApp(ui = ui, server = server)


示例 4:ggvis 和 add_tooltip:

我们也可以使用 ggvis 包.这个包很棒,但是还不够成熟.

We can also use ggvis package. This package is great, however, not enough mature yet.

更新:ggvis 目前处于休眠状态:https://github.com/rstudio/ggvis#status

Update: ggvis is currently dormant: https://github.com/rstudio/ggvis#status

library(ggvis)

ui <- fluidPage(
  ggvisOutput("plot")
)

server <- function(input, output) {

  iris %>%
    ggvis(~Sepal.Width, ~Petal.Width) %>%
    layer_points() %>%
    layer_lines() %>% 
    add_tooltip(function(df) { paste0("Petal.Width: ", df$Petal.Width) }) %>%
    bind_shiny("plot")
}

shinyApp(ui = ui, server = server)

<小时>

已编辑

示例 5:

在这篇文章之后,我在互联网上搜索了它是否可以比示例 3 做得更好.我找到了 this 很棒的 ggplot 自定义工具提示,我相信没有比这更好的了.

After this post I searched internet to see whether it could be done more nicely than example 3. I found this wonderful custom tooltip for ggplot and I believe it can hardly be done better than that.

这篇关于如何在 ggplot2 中悬停时在工具提示上显示 y 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆