r - 颜色 plotly 文本注释

标签 r annotations plotly scatter

我已经对 xy 数据进行了聚类,我想使用 Rplotly 绘制这些数据,其中点按其聚类成员身份着色并且有文本注释簇数和点数占总数的分数。我还试图让这个文本注释与点具有相同的颜色,即按簇着色。

这是我的代码:

library(dplyr)
library(plotly)
set.seed(1)
df <- do.call(rbind,lapply(seq(1,20,4),function(i) data.frame(x=rnorm(50,mean=i,sd=1),y=rnorm(50,mean=i,sd=1),cluster=i)))
df$cluster <- factor(df$cluster)
cluster.colors <- c("#FF6C91","#EF7F47","#D39300","#AAA300","#6BB100")
cluster.centers.df <- dplyr::group_by(df,cluster) %>%
  dplyr::mutate(x=mean(x),y=mean(y),n=n()) %>% unique()
cluster.centers.df$percentage <- cluster.centers.df$n/sum(cluster.centers.df$n)
cluster.centers.df$cluster <- as.character(cluster.centers.df$cluster)


plot_ly(marker=list(size=12),type='scatter',mode="markers",x=df$x,y=df$y,color=df$cluster,colors=cluster.colors,showlegend=F) %>%
  add_annotations(text=sprintf("<b>%s</b>",paste0(cluster.centers.df$cluster,"\n",gsub("\\.00","",as.character(cluster.centers.df$percentage)),"%")),showarrow=T,arrowhead=1,arrowsize=1,x=cluster.centers.df$x,y=cluster.centers.df$y,ax=20,ay=-30,font=list(size=14,color=cluster.colors)) %>%
  layout(xaxis=list(title="X",zeroline=F,showticklabels=F),yaxis=list(title="Y",zeroline=F,showticklabels=F))

但是,这不会根据 cluster.colors 为文本着色。

enter image description here

有什么想法吗?

最佳答案

我无法弄清楚为什么 add_annotations() 方法不起作用,所以我手动创建了注释并在每个 for 循环迭代中添加了颜色。请引用以下代码,如果这能解决您的问题,请告诉我。

library(dplyr)
library(plotly)
set.seed(1)
df <- do.call(rbind,lapply(seq(1,20,4),function(i) data.frame(x=rnorm(50,mean=i,sd=1),y=rnorm(50,mean=i,sd=1),cluster=i)))
df$cluster <- factor(df$cluster)
cluster.colors <- c("#FF6C91","#EF7F47","#D39300","#AAA300","#6BB100")
cluster.centers.df <- dplyr::group_by(df,cluster) %>%
  dplyr::mutate(x=mean(x),y=mean(y),n=n()) %>% unique()
cluster.centers.df$percentage <- cluster.centers.df$n/sum(cluster.centers.df$n)
cluster.centers.df$cluster <- as.character(cluster.centers.df$cluster)

a <- c()
for (i in 1:length(cluster.centers.df$cluster)){
  a[[i]] <- list(text=sprintf("<b>%s</b>",paste0(cluster.centers.df$cluster[i],"\n",gsub("\\.00","",as.character(cluster.centers.df$percentage[i])),"%")),showarrow=T,arrowhead=1,arrowsize=1,x=cluster.centers.df$x[i],y=cluster.centers.df$y[i],ax=20,ay=-30,font=list(size=14,color=cluster.colors[i]))
}
plot_ly(marker=list(size=12),type='scatter',mode="markers",x=df$x,y=df$y,color=df$cluster,colors=cluster.colors,showlegend=F) %>%
layout(annotations = a, xaxis=list(title="X",zeroline=F,showticklabels=F),yaxis=list(title="Y",zeroline=F,showticklabels=F))

关于r - 颜色 plotly 文本注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50765046/

相关文章:

java - Glassfish 3.1 上的 @WebServlet 映射错误

r - 自动计算图例的适当插入值

r - ggbiplot - 改变点的大小

r - 扩展两个值之间的组并计算唯一出现的次数

r - 按组计算的累计最小值和最大值

java - 如何使用camelCase将Hibernate实体字段映射到snake_case(下划线)数据库标识符

java - 一个项目中是否可以只有 1 个 IAnnotationTransformer 实现

python - 在圆环图中隐藏低百分比

python - 在 plotly Dash 中格式化特定的刻度标签

python - 在 Plotly 气泡图中标记特定气泡