Home > Software engineering >  Changing opacity of certain points on scatterplot in Plotly
Changing opacity of certain points on scatterplot in Plotly

Time:11-26

I have a scatterplot produced using Plotly that has certain points highlighted a different colour. However I would like to change opacity of points to that the points that are red remain deep red but the points in purple have a lighter opacity to really emphasise the red points. enter image description here Is there a way in Plotly to do this, I have done in ggplot but now sure how to use opacity=0.5 etc in Plotly to apply to only certain points? Thank you

small edit of data as >3000 rows

BP <- c(117068919, 117072803, 117074604, 117075231, 117076684, 117077326, 
        117078553, 117080817,117083725)

log <-c(0.28777133, 0.540758335, 0.331055266, 1.068186296, 0.075669015, 0.042105513,
        20.156767222, 6.144238628, 5.752272167)

opacity <- c(0.5,0.5,0.5,0.5,0.5,0.5,1,1,1)

data <- data.frame(BP,log,opacity)

fig <- plot_ly(width = 1200, height = 600)
data$highlight <- row.names(data) %in% c("7", "8", "9")   

fig <- fig %>% add_trace(data= data, x = ~BP, y = ~log, color = ~highlight, name = "", mode = "markers", type = "scatter", marker = list(size = 8), colors = c("purple", "red"))

example raw input data

CodePudding user response:

For me it works.
As you can see, we can observe the black dotted line below purple dots.

### Library
library(plotly)

### Data-management
BP <- c(117068919, 117072803, 117074604, 117075231, 117076684, 117077326, 117078553, 117080817, 117083725)
log <- c(0.28777133, 0.540758335, 0.331055266, 1.068186296, 0.075669015, 0.042105513, 20.156767222, 6.144238628, 5.752272167)
data <- data.frame(BP, log, opacity)
data$highlight <- row.names(data) %in% c("7", "8", "9")   
data$opacity <- ifelse(data$highlight==FALSE, 0.5, 0.1)

### Display plot
fig <- plot_ly(width = 1200, height = 600)
fig <- fig %>% add_trace(data= data, 
                         x = ~BP, 
                         y = ~log, 
                         color = ~highlight, 
                         name = "", 
                         mode = "markers", 
                         type = "scatter",
                         marker = list(size = 8), 
                         colors = c("purple", "red"),
                         opacity=opacity)
fig

enter image description here

  • Related