I use subplot function from plotly to plot two graphs (one under another) in my my R-shiny application. The legend is common for both graphs meaning that I have only one column with all legends assembled together.
I want to have the legends near each graph separately in subplot. How can I obtain it?
p1 <-
iris%>%
group_by(Species)%>%
plot_ly(x=~Sepal.Length, color= ~Species, legendgroup=~Species)%>%
add_markers(y= ~Sepal.Width)
p2 <-
iris%>%
group_by(Species)%>%
plot_ly(x=~Sepal.Length, color= ~Species, legendgroup=~Species)%>%
add_markers(y= ~Sepal.Width)
subplot(p1,p2, nrows = 2, shareX = T, shareY = F, titleX = T, titleY = T)
And my desired layout is the following:
This is not achievable as of yet, as per this. This is far from a perfect hack, but if you wished, something like this may be workable -
Use n
to identify the number of unique elements in your colouring variable.
library(plotly)
n <- 3L
clrs <- colorRampPalette(
c(rgb(r = 198, g = 89, b = 17, maxColorValue = 255), '#267dff', 'black')
)(n)
annotations <- c('setosa', 'versicolor', 'virginica')
y_annotation <- seq(0.4, 0.6, length.out = n)
p1 <-
iris %>%
group_by(Species) %>%
plot_ly(x = ~Sepal.Length, color = ~Species, showlegend = FALSE, colors = clrs) %>%
add_markers(y= ~Sepal.Width) %>%
layout(margin = list(r = 100))
for (i in seq_along(annotations)) {
p1 <- add_annotations(
p = p1, text = annotations[i], font = list(color = clrs[i]),
x = 1.05, y = y_annotation[i], xref = 'paper', yref = 'paper',
showarrow = FALSE, xanchor = 'left'
)
}
p2 <-
iris%>%
group_by(Species) %>%
plot_ly(x = ~Sepal.Length, color = ~Species, showlegend = FALSE, colors = clrs) %>%
add_markers(y = ~Sepal.Width) %>%
layout(margin = list(r = 100))
for (i in seq_along(annotations)) {
p2 <- add_annotations(
p = p2, text = annotations[i], font = list(color = clrs[i]),
x = 1.05, y = y_annotation[i], xref = 'paper', yref = 'paper',
showarrow = FALSE, xanchor = 'left'
)
}
subplot(p1, p2, nrows = 2, shareX = T, shareY = F, titleX = T, titleY = T)
This would result in a plot like below.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With