简体   繁体   English

R中的小节中的Plotly和ggplot2悬停文本无法正常工作

[英]Plotly and ggplot2 hover text in barplot from R not working

This is my first question here if I've made any mistake on posting it or explaining my issue I will be happy to hear any feedback. 这是我在这里的第一个问题,如果我在发布或解释问题时遇到任何错误,我将很高兴听到任何反馈。

I'm building a tool in R using Shiny, ggplot and Plotly. 我正在使用Shiny,ggplot和Plotly在R中构建工具。 I've got an example from plotly library where I can see that's possible to have a tooltip when using ggplot to render a graph. 我从plotly 中获得了一个示例,在该示例中,可以看到使用ggplot渲染图形时可以有一个工具提示。

Follows my example code: 遵循我的示例代码:

library(shiny)
library(ggplot2)
library(plotly)
library(dplyr)
library(reshape)

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

server <- function(input, output) {
  output$distPlot <- renderPlotly({
  dat <- data.frame(
  time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
  total_bill = c(14.89, 17.23)
)

p <- ggplot(data=dat, aes(x=time, y=total_bill, fill=time)) +
  geom_bar(stat="identity")
    p <- p + geom_bar(stat = "identity")

    ggplotly(p)
  })
}

shinyApp(ui = ui, server = server)

When I use the above code the tooltip does not show up but if I remove the fill = X2 parameter the tooltip appears: 当我使用上面的代码时,工具提示不会显示,但是如果删除fill = X2参数,则会显示工具提示:

     p <- ggplot(data=dat, aes(x=time, y=total_bill)) +
  geom_bar(stat="identity")

In my application I need to have the fill parameter to separate the "groups" that I have by color and show the legend. 在我的应用程序中,我需要具有fill参数,以按颜色分隔显示的“组”并显示图例。

I have searched for many "workarounds" on the internet using javascript and other solutions, but since it's a native feature from plotly I would like to have this working in a simpler way. 我已经使用javascript和其他解决方案在Internet上搜索了许多“变通方法”,但是由于它是plotly的本机功能,因此我希望以一种更简单的方式进行操作。

Thanks in advance for any help!! 在此先感谢您的帮助!

This is kind of a known issue, you can use this to fix it: 这是一个已知问题,您可以使用此问题来解决:

p <- ggplotly(p)

for (i in 1:length(p$x$data)){
    p$x$data[[i]]$text <- c(p$x$data[[i]]$text, "") 
}
p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM