2

I found this example here which provides a perfect way of getting rid of the extra terms added by ggplotly to the legends.

My problem is that the code in the solution removes everything after a comma , and I have an actual comma is my legends which are in the format of DIC, Spliced

The code is:

for (i in 1:length(myplot$x$data)){
    if (!is.null(myplot$x$data[[i]]$name)){
        myplot$x$data[[i]]$name =  gsub("\\(","",str_split(myplot$x$data[[i]]$name,",")[[1]][1])
    }
}

My original plot has this kind of legend:

enter image description here

After applying the code, I loose my Spliced/Uspliced terms in my legends

enter image description here

Maral Dorri
  • 468
  • 5
  • 17
  • Can you show your actual data and plot? Forget about that other answer, it’s quite a wonky approach that shouldn’t be necessary to generate proper legends. – Konrad Rudolph Mar 08 '21 at 10:32

1 Answers1

3

So plotly always turns the new legend to be (orignal_legend,1)(Weird). Is it always ,1) ? or can be ,2) or any other number. I don't know.

If your original legend is (DIC, Spliced, 1) it will become ((DIC, Spliced, 1), 1) with plotly. So you have to remove the beginning round brackets and ending ,1) from the legend. Try this regex with gsub :

for (i in 1:length(myplot$x$data)){
  if (!is.null(myplot$x$data[[i]]$name)){
    myplot$x$data[[i]]$name = gsub('^\\(|,\\d+\\)$', '', myplot$x$data[[i]]$name)
  }
}

As mentioned earlier I am not sure if it is going to be always ,1) or can be ,2) as well, so to be on the safer side I have used \\d+ which will remove any number at the end of the string.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • ‘plotly’ doesn’t *generally* do this, no. It does that when the legend combines multiple aesthetics, and the the legend title then is a comma-separated list of these aesthetics. E.g. `(‹color›, ‹fill›)`. – Konrad Rudolph Mar 08 '21 at 10:48