7

I using ggplotly to plot a graph. I am using the tooltip function to represent the values in the barchart when the cursor is moved on the top of the graphs.

 Source_Data <-
 data.frame(
 key = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
 Product_Name = c(
  "Table",
  "Table",
  "Chair",
  "Table",
  "Bed",
  "Bed",
  "Sofa",
  "Chair",
  "Sofa"
 ),
 Product_desc = c("XX", "XXXX", "YY", "X", "Z", "ZZZ", "A", "Y", "A"),
 sd = c(0.1, 0.3, 0.4, 0.5, 0.6, 0.7, 0.7, 0.8, 0.5),
 Cost = c(1, 2, 3, 4, 2, 3, 4, 5, 6)

 )


ggplotly((
Source_Data %>%
ggplot(
  aes(
    Product_Name,
    Cost,
    ymin = Cost - sd,
    ymax = Cost + sd,
    fill = Product_desc,
    text = paste("Product Name:", Product_Name, "<br>", "Cost:", Cost)
  )
  ) +
  geom_col(position = position_dodge2(width = .9, preserve = "single")) +
  geom_errorbar(position = position_dodge2(
  width = .9,
  preserve = "single",
  padding = .5
  )) +
  geom_text(
  aes(y = Cost + sd, label = Cost),
  position = position_dodge2(width = .9),
  vjust = -1
  ) +
  facet_wrap( ~ key, scales = "free_x", strip.position = "bottom") +
  theme(strip.placement = "outside") +
  theme_bw()
  ),
  tooltip = "text"
  )

When i move the cursor over the bars I am getting the text values, thats fine. When i move it on top of the error bars I am getting the text values in different color. Is there a way that I can change the Background color of this hover text.

I am open for all Suggestions.

zabop
  • 6,750
  • 3
  • 39
  • 84
David Chris
  • 255
  • 4
  • 16

1 Answers1

9

You can add %>% layout(hoverlabel=list(bgcolor="white")) after your ggplotly(...) call to set the hover label background color to white.

In general, you can set any Plotly layout attribute from https://plot.ly/r/reference/ in this manner on any figure created with plot_ly() or ggplotly().

nicolaskruchten
  • 26,384
  • 8
  • 83
  • 101
  • Thank you so much :) This works. Is there any way to disable the hover label when we move it over the error bars ? I want the Hover to just work for the bars alone and not the error bars. – David Chris Mar 30 '20 at 00:14
  • @David Chris You can disable `hoverinfo` for particular traces using `ggplotly(my_plot) %>% style(hoverinfo = 'none', traces = c(1, 2, 3, ...))`. So you just need to work out which trace number(s) you want to disable (sometimes the hoverinfo will say `trace 1` for example - although this is not necessarily correct!!), and include them in place of `1, 2, 3, ...`. Trial and error is a good way to find the trace number. – hugh-allan Apr 28 '22 at 01:46