Home > database >  R: How to customize plotly interactive hover window?
R: How to customize plotly interactive hover window?

Time:06-09

Here I have interactive barplot given by ggplotly. The only issue is that when I move mouse around bars, in the "model" category there is strange number instead of A or B (see the picture). Is it possible to customize plotly popup windows?

   df <- data.frame (model  = c("A", "A","B","B"),
                      year = c("2022","2021","2022","2021"),
                      sale = c(350,170,300,150),
                      change = c(180,NA,150,NA),
                      percent = c(105.8,NA,100,NA),
                      info = c("180, 105.8%",NA,"300,100%",NA)
                      )




#ggplot
plot <- ggplot(df, aes(fill=year, y=model, x=sale))   
    geom_bar(position="dodge", stat="identity")   geom_text(aes(label=info, x=1.11*max(sale),), fontface='bold')  xlim(0, 1.2*max(df$sale))  
 theme(legend.position="bottom") labs(fill = " ") 
  scale_fill_brewer(palette = "Paired")



ggplotly(plot)

enter image description here

CodePudding user response:

Personally, i avoid using ggplotly() as it more often than not formats the visuals in a way that i do not want.

A full plotly approach could look like this:

plot_ly(
  data = df,
  x = ~sale,
  y = ~model,
  color = ~year,
  text = ~year,
  type = "bar") %>% 
  add_trace(
    x = ~max(df$sale) * 1.1,
    y = ~model,
    type = 'scatter',
    mode = 'text',
    text = ~info,
    showlegend = FALSE
  ) %>% 
  style(hovertemplate = paste("Sale: %{x}",
                              "Model: %{y}",
                              "Year: %{text}",
                              sep = "<br>"))

enter image description here

You could also try to append the style() object to your ggplotly() object. I am not sure if this will work however.

CodePudding user response:

For some reason, it works better if you use x=model and flip the axes:

plot <- ggplot(df, aes(fill=year, x=model, y=sale))   
  geom_bar(position="dodge", stat="identity")   geom_text(aes(label=info,y=1.11*max(sale),), fontface='bold') 
  ylim(0, 1.2*max(df$sale))  
  theme(legend.position="bottom") labs(fill = " ") 
  scale_fill_brewer(palette = "Paired") 
  coord_flip()

ggplotly(plot)

enter image description here

  • Related