I created a plot using ggplot2 with two different aesthetics for colour and shape. When I convert the ggplot2 plot to plotly via plotly::ggplotly() the different aes seem to create problems.
library(ggplot2) # Version ‘3.4.4’
library(plotly) # Version ‘4.10.4’
library(dplyr)
test_data <- head(iris) |>
mutate(ID = rank(Sepal.Length),
category1 = sample(c("A", "B"), 6, replace = TRUE),
category2 = sample(c("C", "D"), 6, replace = TRUE))
#ggplot
gg_plot <- ggplot(data = test_data) +
geom_line(mapping = aes(x = Sepal.Length,
y = Sepal.Width,
color = category1)) +
geom_point(mapping = aes(x = Sepal.Length, y = ID, shape = category2))
gg_plot
#plotly
plotly_plot <- plotly::ggplotly(gg_plot)
plotly_plot
ggplot2 plot:
plotly plot:
The same or similar problems where already reported a few years ago:
https://github.com/plotly/plotly.R/issues/572
Convert ggplot2 graph to plotly - legend, labels and values
However, the workarounds either do not work for my case or seem very awkward to implement within a dynamic function.
Does anyone know if there is a somewhat easy way to convert a ggplot2 plot with multiple aesthetics to a plotly plot while keeping the legends?
Edit: I phrased my question wrong. I want to keep the legends and the displayed category values (e.g. "C" instead of "(C,1)").


