I want to produce a plot via R plotly with independent legends while respecting the colorscale.
This is what I have:
library(plotly)
X <- data.frame(xcoord = 1:6,
ycoord = 1:6,
score = 1:6,
gender = c("M", "M", "M", "F", "F", "F"),
age = c("young", "old", "old", "old", "young", "young"))
plot_ly(data = X, x = ~xcoord, y = ~ycoord, split = ~interaction(age, gender),
type = "scatter", mode = "markers",
marker = list(color = ~score,
colorbar = list(len = .5, y = .3)))
As you can see, the colorbar is messed up and the two categories are entangled.
I need to have separate legends for age
(young vs old) and gender
(M vs F), that can be clicked independently from one another. This would be the expected outcome:
Edit 1
This is the equivalent with ggplot2
:
gg <- ggplot(X, aes(x = xcoord, y = ycoord)) +
geom_point(aes(color = score, shape = gender, alpha = age), size = 5) +
scale_shape_manual(values = c("M" = 19, "F" = 19)) +
scale_alpha_manual(values = c("young" = 1, "old" = 1))
ggplotly(gg)
It does display correctly in ggplot, but breaks when applying ggplotly()
.
Please note that I would favor a solution with the native plotly
plot, rather than a post hoc ggplotly()
fix as has been proposed in other posts.
Edit 2
Although the current answers do disentangle the two legends (age
and gender
), they are not functional. For instance, if you click on the young
level, the whole age
legend will be toggled on/off. The objective here is that each sub level of each legend can be toggled independently from the others, and that by clicking on the legend's levels, the dot will show/hide accordingly.
coloraxis
in thelayout
according to plotly.com/r/colorscales/#share-color-axis ; while it works with the heatmap example,plot_ly
throws a warning that this attribute does not apply to scatter[plot] objects.