2
votes

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’
> 
1
it's the correct stack value.MLavoie
@MLavoie - it should have shown 20, instead it is showing 135 - how is this correct ?user3206440
stack! just add-up the first three starting from the topMLavoie
@MLavoie how do I get 20 to be displayed instead of the sum - ie. individual values for each bar - what kind of chart in plotly can give it ?user3206440

1 Answers

2
votes

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)