Reputation: 1932
BACKGROUND: I am preparing an interactive plot via a tooltip in plotly
via the ggplotly()
function. The recommend workflow for creating the tooltip information is to add an unknown aestetic in the ggplot plot, and then use this unknown aestetic later in the ggplotly()
function.
PROBLEM: Adding an unknown aestetic disrupts the order of the fill variable. Is there a workaround to this?
ADDITIONAL INFORMATION: This reprex can be solved by letting ggplot
do the counting via geom_bar()
. This will however not work in my real problem.
library(dplyr)
library(ggplot2)
a <- diamonds %>%
group_by(color, cut, clarity) %>%
summarise(n = n()) %>%
ggplot(aes(x = color, y = n, fill = cut))+
geom_col()
#> `summarise()` has grouped output by 'color', 'cut'. You can override using the `.groups` argument.
b <- diamonds %>%
group_by(color, cut, clarity) %>%
summarise(n = n()) %>%
ggplot(aes(x = color, y = n, fill = cut))+
geom_col(
aes(text = paste("Count:", n))
)
#> `summarise()` has grouped output by 'color', 'cut'. You can override using the `.groups` argument.
#> Warning: Ignoring unknown aesthetics: text
a
b
Created on 2022-03-21 by the reprex package (v2.0.1)
This is how the call to ggplotly()
will look
library(plotly)
ggplotly(b,
tooltip = "text")
Upvotes: 1
Views: 115
Reputation: 4636
The text
should be called within ggplot
function so I think this gets you what you need:
b <- diamonds %>%
group_by(color, cut, clarity) %>%
summarise(n = n()) %>%
ggplot(aes(x = color, y = n, fill = cut, text = paste("Count:", n)))+
geom_col()
ggplotly(b,
tooltip = "text")
Upvotes: 1