Reputation: 8454
How can I format the hoverinfo()
or hovertext()
of my grouped plotly barchart in order to display the data as the following:
Animals:Giraffe
SF_ZOO:20
Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)
library(plotly)
fig <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF_ZOO',marker=list(color="#556361"),
hoverinfo = paste(Animals,SF_Zoo))
fig <- fig %>% add_trace(y = ~LA_Zoo, name = 'LA_ZOO',marker=list(color="#A72608"),
hoverinfo = paste(Animals,SF_Zoo))
fig <- fig %>% layout(yaxis = list(title = 'Count'), barmode = 'group')
fig
Alternatively I could use ggplotly()
solution.
Upvotes: 0
Views: 724
Reputation: 1090
Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo) %>% pivot_longer(cols = contains("Zoo")) %>%
mutate(label=paste0("<b>", name, "</b><br>", Animals))
gg <- ggplot(data, aes(y=value, x=Animals, fill=name, text=label)) + geom_bar(stat="identity")
ggplotly(gg, tooltip = "text")
Upvotes: 2
Reputation: 84709
You can use hovertemplate
:
library(plotly)
Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)
library(plotly)
fig <- plot_ly(
data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF_ZOO',
marker=list(color="#556361"),
hovertemplate = paste("Animals: %{x}" , "<br>SF_Zoo: %{y}", "<extra></extra>")
)
fig <- fig %>% add_trace(
y = ~LA_Zoo, name = 'LA_ZOO',marker=list(color="#A72608"),
hovertemplate = paste("Animals: %{x}" , "<br>LA_Zoo: %{y}", "<extra></extra>")
)
fig <- fig %>% layout(yaxis = list(title = 'Count'), barmode = 'group')
fig
Upvotes: 2