Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legend near each plot in subplot plot_ly in R

Tags:

r

subplot

plotly

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)

The result of the above code

And my desired layout is the following: The desired result

like image 759
Rfreak Avatar asked Oct 28 '22 08:10

Rfreak


1 Answers

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.

enter image description here

like image 116
Ameya Avatar answered Nov 15 '22 06:11

Ameya