r - 在堆积条形图中悬停时 plotly 给出不正确的文本

标签 r plotly r-plotly ggplotly

我正在将 plotly 与 RStudio 结合使用。

plotly 在悬停时为图表中的堆叠条形提供不正确的文本(最顶部的条形除外)。

可重现的示例

  df <- data.frame(
    make = rep(c('Toyota', 'Honda', 'Volkswagen'),4),
    segment =c(rep('high',3), rep('mid',3), rep('low',3), rep('entry',3) ),
    sales=c( 25,35,75, 35,35,30, 45,25,10, 80, 80, 20)
  )

df
         make segment sales
1      Toyota    high    25
2       Honda    high    35
3  Volkswagen    high    75
4      Toyota     mid    35
5       Honda     mid    35
6  Volkswagen     mid    30
7      Toyota     low    45
8       Honda     low    25
9  Volkswagen     low    10
10     Toyota   entry    80
11      Honda   entry    80
12 Volkswagen   entry    20

  p <- ggplot(df, aes(x=make, y=sales) ) +
    geom_bar(stat="identity", aes(fill=segment), position = "stack")
  ggplotly(p)

我在RStudio中得到的结果如下图所示。正如您所看到的,除了顶部堆叠栏之外,其他所有内容在悬停时都会给出错误的文本

悬停时的文本不正确 - 根据 df 中的数据,sales 的正确值为 20 - 相反它显示 135 - 数据 - 12 大众汽车入门 20 enter image description here

悬停时的正确文本 - 仅在堆栈中最顶部的栏上观察到。 enter image description here

> packageVersion('ggplot2')
[1] ‘2.2.1’
> packageVersion('plotly')
[1] ‘4.5.6’
> 

最佳答案

也许你可以尝试添加它:

p <- ggplot(df, aes(x=make, y=sales, fill=segment, text=paste("sales original value", sales))) + geom_bar(stat="identity")
ggplotly(p)

如果您只想显示销售额,您还可以使用:

ggplotly(p, tooltip = c("text"))

使用 Shiny :

library(shiny)
ui <- fluidPage(
  plotlyOutput("plot")
)

server <- function(input, output) {
  output$plot <- renderPlotly({  
p <- ggplot(df, aes(x=make, y=sales, fill=segment, text=paste("sales original value:", sales))) + geom_bar(stat="identity")
ggplotly(p, tooltip = c("text"))
  })
}

shinyApp(ui, server)

关于r - 在堆积条形图中悬停时 plotly 给出不正确的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43083554/

相关文章:

r - 过滤串扰的两个键

r - r 中阿姆斯壮数的程序

R bnlearn eval 内部函数

r - 在 renderPlotly 单击事件中使用 closePoints 时出现 Shiny 错误

python - 如何为绘图条形图中的某些条设置特定颜色?

r - 通过绘图下拉菜单切换显示的轨迹

r - Plotly:如何在箱线图上添加中线

r - ggplot2 中的数字格式轴标签?

r - 出于调试目的将 Shiny 的响应式(Reactive) df 打印到控制台 (glipse(myreactive_df)?

python - Plotly:如何重写标准破折号应用程序以在 JupyterLab 中启动它?