I am working with the R programming language.
I made the following graph for some random data:
library(plotly)
myFun <- function(n = 5000) {
a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
paste0(a, sprintf("d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}
file = data.frame(var1 = rnorm(100,100,100), var2 = rnorm(100,100,100) , var4 = myFun(100))
file$ratio = file$var1/file$var2
file[is.na(file)] <- 0
file$color = ifelse(file$ratio < median(file$ratio), "big", "small")
pal <- c("red", "blue")
pal<- setNames(pal, c("big", "small"))
p = plot_ly(file, x = ~log(var1), y = ~var2, text = ~paste("name:", var4), color = ~color, colors = pal, type = "scatter")
p = p %>% layout(title = 'title1', xaxis = list(title = 'title2'), yaxis = list(title = 'title3'))
p =p %>% add_trace( text = paste("name :", file$var4, "<br> var1_val :", file$var1, "<br> var2_val:", file$var2, "<br> Ratio :", file$ratio), hoverinfo = "text", showlegend = TRUE)
This produces the following graph:
Everything seems to be working - the only problem is that the legend seems to be duplicated.
I have been trying different combinations (e.g. removing certain options with the plotly calls) to see if I can somehow de-duplicate the legend - but so far nothing seems to be working.
Can someone please show me how to do this?
Thanks!
CodePudding user response:
Either use showlegend = FALSE
as by default inherit = TRUE
in add_trace
to inherit all the attributes from the plot_ly
p =p %>%
add_trace( text = paste("name :", file$var4, "<br> var1_val :", file$var1, "<br> var2_val:", file$var2, "<br> Ratio :", file$ratio),
hoverinfo = "text", showlegend = FALSE)
Or use inherit = FALSE
with showlegend = TRUE
p %>%
add_trace( text = paste("name :", file$var4, "<br> var1_val :", file$var1, "<br> var2_val:", file$var2, "<br> Ratio :", file$ratio), hoverinfo = "text", showlegend = TRUE, inherit = FALSE)