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.
我尝试用R绘制一个散点图,其中的点根据渐变被着色,在此之上,我想对几个点进行文本注释,我希望文本注释的颜色遵循相同的颜色渐变。
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))
这使:
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:
增加文字,但没有颜色编码:
Any idea how to get the text colored according df$y
with the c("blue","red")
gradient ?
你知道如何用c(“蓝色”、“红色”)渐变绘制文本颜色吗?
1 个解决方案
#1
2
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.
我不知道如何用阴谋来达到这个目的。也许有人会有更好的主意,但与此同时,简单地使用ggplotly来获得你想要的东西可能会更容易。
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"))
#1
2
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.
我不知道如何用阴谋来达到这个目的。也许有人会有更好的主意,但与此同时,简单地使用ggplotly来获得你想要的东西可能会更容易。
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"))