Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set alpha of legend in ggplot/Plotly

Tags:

r

ggplot2

plotly

How do I get the legend in a plotly plot to not inherit the alpha values used in a plot?

I know how to do this with ggplot2: guides(colour = guide_legend(override.aes = list(alpha=1))) but this does not translate to plotly.

is there a similar option for plotly? When converting from ggplot to plotly it seems to pick up on the alpha value for the legend no matter what I do.

Example Code:

library(ggplot2)
library(plotly)

D <- rbind(beaver1,beaver2)
D$beaver= c(rep('A',nrow(beaver1)),rep('B',nrow(beaver2)))

p <- ggplot(D,aes(x=time,y=temp,color=beaver,group=day))+
  geom_point(alpha=.1,show.legend = F)+
  geom_line(alpha=.1,show.legend = F)+
  geom_smooth(se=F)

ggplotly(p)

The ggplot version:

ggplot version

The plotly version:

enter image description here

like image 999
Bishops_Guest Avatar asked Sep 14 '25 08:09

Bishops_Guest


1 Answers

As far as I know you cannot control the opacity of the legend.

If you look at the string output of ggplotly you can see that there are 2x3 traces. 3 traces for each beaver, one for the markers, one for the connecting line and one for the smooth line. The first trace determines the legend, so you could just rearrange your ggplot and it should work.

library(ggplot2)
library(plotly)

D <- rbind(beaver1,beaver2)
D$beaver= c(rep('A',nrow(beaver1)),rep('B',nrow(beaver2)))

p <- ggplot(D,aes(x=time,y=temp,color=beaver,group=day))+
  geom_smooth(se=F)+
  geom_point(alpha=.1,show.legend = F)+
  geom_line(alpha=.1,show.legend = F)


gp <- ggplotly(p)
gp

enter image description here

The other solution would be to turn on and off the legends.

gp$x$data[[1]]$showlegend <- FALSE
gp$x$data[[2]]$showlegend <- FALSE
gp$x$data[[5]]$showlegend <- TRUE
gp$x$data[[6]]$showlegend <- TRUE
like image 100
Maximilian Peters Avatar answered Sep 17 '25 01:09

Maximilian Peters