简体   繁体   中英

R: Plotly Legend Duplicated?

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("%04d", 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 (eg 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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM