R 使用ggplotly向plotly图形添加自定义工具提示时出错

R 使用ggplotly向plotly图形添加自定义工具提示时出错,r,shiny,plotly,r-plotly,ggplotly,R,Shiny,Plotly,R Plotly,Ggplotly,这是一个非常特殊的问题,因此我在下面提供了一个最小的可复制示例: library(dplyr) library(ggplot2) library(magrittr) library(plotly) library(shiny) example_data <- tibble( target = factor(rep(LETTERS[1:5], each = 6)), error = runif(30, -1, 1), model = factor(rep(c('Model 1'

这是一个非常特殊的问题,因此我在下面提供了一个最小的可复制示例:

library(dplyr)
library(ggplot2)
library(magrittr)
library(plotly)
library(shiny)

example_data <- tibble(
  target = factor(rep(LETTERS[1:5], each = 6)),
  error = runif(30, -1, 1),
  model = factor(rep(c('Model 1', 'Model 2'), times = 15)),
  type = factor(rep(rep(c('Type 1', 'Type 2', 'Type 3'), each = 2), times = 5))
)

ui <- fluidPage(
  plotlyOutput('plot')
)

server <- function(input, output) {
  output$plot <- renderPlotly({
    p <- example_data %>%
      #mutate(label = paste0(model, ' (', type, ')')) %T>%  # <- doesn't work
      mutate(label = paste0(model, ' (Foo)')) %T>%  # <- does work
      {print(., n = Inf)} %>%  # debugging
      ggplot(aes(x = target, y = error, text = label)) +
        geom_violin(aes(fill = target), show.legend = FALSE) +
        geom_jitter(width = 0.1) +
        coord_flip()

    ggplotly(p, tooltip=c('text'))
  })
}

shinyApp(ui, server)
我正在努力破译这与我的代码的关系。另一方面,如果我将其中一列与伪文本字符串(Foo)组合在一起,则工具提示不会出错。通过切换是否对第21/22行进行注释,可以在这两种方法之间切换


也许我在这里遗漏了一些明显的东西,但我完全搞不清楚到底发生了什么。有人有什么想法或者这可能是一个bug吗?

我已经找到了答案,所以我将与大家分享,以防有人遇到这个问题。事实证明,这个问题与shiny或plotly无关,而是与ggplot有关

似乎在初始映射中设置
文本
美学对
geom\u小提琴
有连锁反应。特别是,尽管
text
不是已知的
geom_小提琴的美学,但它的加入改变了小提琴的分组。由于每个数据点的标签都是唯一的,因此我试图为每个数据点单独创建一个小提琴图——这是不可能的。通过在
geom_
映射中设置
group=target
,问题得到了解决


很难说这是一个bug还是一个特性,因此我将进一步剥离该示例,并将其作为问题添加到ggplot repo中。

这不是
geom\u小提琴的问题。您正在将一个文本变量传递给
geom_小提琴
,该变量在单个小提琴中不是常量。例如,尝试使用
text=target
,或任何其他对每把小提琴都是常量的变量
text=label
可用于
geom\u jitter
aes
Warning in max(data$density) :
  no non-missing arguments to max; returning -Inf
Warning: Error in order: argument 1 is not a vector