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

时间:2017-03-22 15:51:00

标签: r plot ggplot2 shiny plotly

这是我的第一个问题,如果我在发布或解释我的问题时犯了任何错误,我将很乐意听到任何反馈。

我正在使用Shiny,ggplot和Plotly在R中构建一个工具。我从plotly library得到了一个例子,我可以看到在使用ggplot渲染图形时可以有一个工具提示。

按照我的示例代码:

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)

当我使用上面的代码时,工具提示没有显示,但如果我删除了fill = X2参数,则会显示工具提示:

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

在我的应用程序中,我需要使用fill参数来分隔我拥有的“组”颜色并显示图例。

我使用javascript和其他解决方案在互联网上搜索了许多“变通办法”,但由于它是一个原生的功能,我想让它以更简单的方式工作。

提前感谢您的帮助!!

1 个答案:

答案 0 :(得分:2)

这是一个已知问题,你可以用它来修复它:

p <- ggplotly(p)

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