Search code examples
rplotlyopacity

R plto_ly or ggplot: fade in line with changing opacity


In an plot_ly plot I want a line to fade in using the opacity parameter. I thought I group the data into as many groups as there are datapoints and add an opacity parameter. However the groups do not get connected so there is nothing plotted.

library(plotly)
xg = as.character(c(1:100))  
df <- data.frame(x = 1:100,xg = as.factor(xg), y = 1:100, opacity =0.01*(1:100))

df <-group_by(df, xg)
plot_ly(df)%>%
add_trace( x =~x, y= ~y, opacity = ~opacity )

And it doesent even work with markers, the opacity is constant:

library(plotly)
xg = as.character(c(1:100))  
df <- data.frame(x = 1:100,xg = as.factor(xg), y = 1:100, opacity =0.01*(1:100))

df <-group_by(df, xg)
plot_ly(df)%>%
add_markers( x =~x, y= ~y, opacity = ~opacity )

Solution

  • I think this is what you're looking for, but correct me if I'm wrong. Here I'll make the plot in ggplot, then covert to plotly.

    library(ggplot2)
    library(plotly)
    p <- ggplot(df,aes(x =x, y = y,alpha = opacity))+
        geom_point()+
        theme_classic()
    
    ggplotly(p)
    

    enter image description here

    I think what you're looking for to "fade" the line is the alpha argument.