Search code examples
rggplot2ggplotly

colored geom bar - plotly


How do you resolve the double labels when you hover over the filled geom_bar? This doesn't occur in the unfilled geom_bar


# no fill
library(plotly)

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)) +
   geom_bar(stat="identity")

p <- ggplotly(p)

# filled

library(plotly)

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 <- ggplotly(p)

source: https://plot.ly/ggplot2/geom_bar/


Solution

  • This repeat arises because you have time in your aes call twice (x and fill, which is common).

    You just need to specify which arguments in aes you want to use in the graph with the tooltip argument.

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

    In this case, I used "x" and "y", but you could also have used "fill" instead.

    Alternatively, you can also force labels (which sometimes comes in handy) like the following:

    p <- ggplot(data=dat, aes(x=time, y=total_bill, fill=time,
                              label = time, label2 = total_bill)) +
      geom_bar(stat="identity")
    
    p <- ggplotly(p, tooltip = c("label", "label2"))