r - 彩色绘图文本注释
问题描述
我有聚类xy
数据,我想使用R
's绘制这些数据,plotly
其中点按其聚类成员身份着色,并且有文本注释聚类编号和总数中的分数。我还试图让这个文本注释与点的颜色相同,即按集群着色。
这是我的代码:
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
。
任何的想法?
解决方案
我无法弄清楚为什么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))
推荐阅读
- java - 如何使用包含文件的 JAVA 发送 Post HTTP 请求
- swift - 如何解决 swift + firebase 循环图像问题?
- python - 我想在 python 的饼图中绘制 2 个变量
- java - 当域对象更改但数据库没有更改时,需要处理哪些设计模式?
- c# - 如何将两个相同列的数据表单元格合并到一个单元格中,用 C# 分隔逗号?
- reactjs - 使用反应路由器获取数据并将其传递给路由的正确方法是什么?
- pvs-studio - Linux 上的 PVS Studio - 命令行返回码
- python - 如果超过 3 个连续的 NaN,则删除列
- windows-installer - WiX 工具集自定义操作 - 无法通过 WiX 项目找到 dll 和引用
- javascript - 使用一个主类具有我在组件中需要的所有类。那是坏方法吗?