3
votes

I'm trying to make a scatter plot with R plotly, where the points are colored according to a gradient, and on top of that I'd like to text annotate several points, where I'd like the color of the text annotation to follow the same color gradient.

Here's a toy data:

set.seed(1)
df <- data.frame(x=rnorm(100),y=-1*log10(runif(100,0,1)),id=paste0("id",1:100),stringsAsFactors = F)

Here's the colored scatter plot:

library(plotly)
library(dplyr)

scatter.plot <- plot_ly(type='scatter',mode='markers',x=~df$x,y=~df$y,color=~df$y,colors=c("blue","red"),showlegend=FALSE) %>%
  layout(xaxis=list(title="Effect Size",zeroline=F),yaxis=list(title="Significance",zeroline=F))

which gives: enter image description here

Then, I'm trying to add the text annotation.

First, I'm creating the annotation data:

ann.df <- df[sample(100,5,replace = F),]

Then I'm trying this to add the annotation text:

scatter.plot <- scatter.plot %>% layout(annotations = list(x=ann.df$x,y=ann.df$y,text=ann.df$id,xref="x",yref="y",showarrow=T,arrowhead=5,arrowcolor=ann.df$y,ax=20,ay=-40,colors=c("blue","red"),font=list(size=15,color=ann.df$y,colors=c("blue","red"))))

The text is added but not color coded: enter image description here

Any idea how to get the text colored according df$y with the c("blue","red") gradient ?

1
Tricky, adding HTML to annotations does not help and the font color can only be provided for all annotations. Probably you'd need to hack it in with Javascript but I guess the result will be rather hard to see if the points in proximity have a similar color. - Maximilian Peters
@MaximilianPeters Could one use colorRampPalette in a clever way to explicitly create a column of colours in df? The next step would be to display the colourscales separately. - Ameya

1 Answers

2
votes

I am not sure how to achieve this using plotly. Maybe someone will have a better idea but in the meantime, it might be easier by simply using ggplotly to get what you want.

You could try this:

a <- ggplot(data = df, aes(x = x, y = y, color = y, label1 = x, label2 = y)) + 
  geom_point() + 
  theme_bw() + 
  scale_color_continuous(low = "blue", high = "red")

b <- a +  
  geom_text(data = ann.df, aes(x=x, y=y, label = id, color = y), hjust = 0, nudge_x = 0.05)

ggplotly(b, tooltip = c("label", "label1", "label2"))

enter image description here