Search code examples
rggplot2ggplotly

Different tooltips after scale shift with ggplotly


I am trying to make a combined bar + point chart with ggplot and ggplotly. I am using a scale shift for the bars so that the origin starts at 100. I'm successful, but the tooltip values are different for bars and points: bars have shifted values while points retain original values. I would like to have same 'correct' (non-shifted values) for both of the tool tips. Is this possible?

library(ggplot2)
library(dplyr)
library(ggthemes)
library(plotly)

set.seed(369)
values <- round(100 + rnorm(6) * 10, 2)
df <- data.frame(Year = rep(2014:2019, 2), 
                  value = rep(values, 2),
                  Indicator = "Indicator1",
                  Type = rep(c("Bar", "Point"), each = 6))

p <- ggplot(df, aes(value))

bars <- df  %>%
  filter(Type == "Bar")

points <- df  %>%
  filter(Type == "Point")

t_shift <- scales::trans_new("shift",
                             transform = function(x) {x - 100},
                             inverse = function(x) {x + 100})

pl <- p +
  geom_bar(data = bars,
           aes(fill = Indicator, group = Indicator,x = Year, y = value), stat = "identity", position = "dodge") +
  geom_point(data = points,  aes(x = Year, y = value, group = Indicator)) +
  scale_fill_manual(values=c("#00A6CE", "#A83D72"))+
  theme_tufte() +
  theme(legend.title = element_blank()) +
  scale_y_continuous(limits = c(80, 120), trans = t_shift) 

ggplotly(pl, tooltip = c("value"))

Different tooltip values


Solution

  • I believe the easiest way around is to copy value for both datasets and include it in another variable of the ggplot chart.

    This code works in my computer:

    bars$Value <- bars$value
    points$Value <- points$value
    
    
    pl <- p +
      geom_bar(data = bars,
               aes(fill = Indicator, group = Indicator,x = Year, y = value,z=Value), stat = "identity", position = "dodge") +
      geom_point(data = points,  aes(x = Year, y = value, group = Indicator,z=Value)) +
      scale_fill_manual(values=c("#00A6CE", "#A83D72"))+
      theme_tufte() +
      theme(legend.title = element_blank()) +
      scale_y_continuous(limits = c(80, 120), trans = t_shift) 
    
    ggplotly(pl, tooltip = c("Year","Value"))