简体   繁体   English

R:Plotly 图例重复?

[英]R: Plotly Legend Duplicated?

I am working with the R programming language.我正在使用 R 编程语言。

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.我一直在尝试不同的组合(例如使用 plotly 调用删除某些选项)以查看我是否可以以某种方式删除图例的重复项 - 但到目前为止似乎没有任何效果。

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默认情况下使用showlegend = FALSE inherit = TRUEadd_trace中继承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或者使用inherit = FALSEshowlegend = 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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