user3206440
user3206440

Reputation: 5049

plotly giving incorrect text on hover in stacked bar charts

I'm using plotly with RStudio.

plotly is giving incorrect text on hover for stacked bars in the chart except for the top most bar.

Reproducible example

  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)

What I get in RStudio is as in the pictures below. As you would see except for the top stacked bar, everything else is giving the wrong text on hover

Incorrect text on hover - based on data in df the correct value for sales is 20 - instead it is showing 135 - data - 12 Volkswagen entry 20 enter image description here

Correct text on hover - only observed for the top most bar in stack. enter image description here

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

Upvotes: 2

Views: 1690

Answers (1)

MLavoie
MLavoie

Reputation: 9836

maybe you could try adding it with:

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

and if you want to show only sales, you can also use:

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

using 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)

Upvotes: 2

Related Questions