我正在尝试使用 ggvis 重现 ggplot2 图。该图旨在表示点的坐标(来自对应分析)及其簇(hclust)标准色散椭圆。
TL; 博士
我想制作一个基于多个数据集的多层 ggvis 图。因此,功能/管道方法阻止我对其中一个层进行分组,而不是对另一层进行分组。
整个(简要评论)代码在那里:https ://gist.github.com/RCura/a135446cda079f4fbc10
下面是创建数据的代码:
a <- rnorm(n = 100, mean = 50, sd = 5)
b <- rnorm(n = 100, mean = 50, sd = 5)
c <- rnorm(n = 100, mean = 50, sd = 5)
mydf <- data.frame(A = a, B = b, C = c, row.names = c(1:100))
library(ade4)
myCA <- dudi.coa(df = mydf,scannf = FALSE, nf = 2)
myDist <- dist.dudi(myCA, amongrow = TRUE)
myClust <- hclust(d = myDist, method = "ward.D2")
myClusters <- cutree(tree = myClust, k = 3)
myCAdata <- data.frame(Axis1 = myCA$li$Axis1, Axis2 = myCA$li$Axis2, Cluster = as.factor(myClusters))
library(ellipse) # Compute Standard Deviation Ellipse
df_ellipse <- data.frame()
for(g in levels(myCAdata$Cluster)){
df_ellipse <- rbind(df_ellipse,
cbind(as.data.frame(
with(myCAdata[myCAdata$Cluster==g,],
ellipse(cor(Axis1, Axis2),
level=0.7,
scale=c(sd(Axis1),sd(Axis2)),
centre=c(mean(Axis1),mean(Axis2))))),
Cluster=g))
}
我可以通过 ggplot2 绘制它:
library(ggplot2)
myPlot <- ggplot(data=myCAdata, aes(x=Axis1, y=Axis2,colour=Cluster)) +
geom_point(size=1.5, alpha=.6) +
geom_vline(xintercept = 0, colour="black",alpha = 0.5, linetype = "longdash" ) +
geom_hline(xintercept = 0, colour="black", alpha = 0.5, linetype = "longdash" ) +
geom_path(data=df_ellipse, aes(x=x, y=y,colour=Cluster), size=0.5, linetype=1)
myPlot
但我找不到如何使用 ggvis 来绘制它。
我可以绘制 2 个不同的图层:
library(ggvis)
all_values <- function(x) { paste0(names(x), ": ", format(x), collapse = "<br />")}
ggDF <- myCAdata
ggDF$name <- row.names(ggDF)
## Coordinates plot
myCoordPlot <- ggvis(x = ~Axis1, y = ~Axis2, key := ~name, data = ggDF) %>%
layer_points(size := 15, fill= ~Cluster, data = ggDF) %>%
add_tooltip(all_values, "hover")
myCoordPlot
椭圆图(不要求工具提示)
myEllPlot <- ggvis(data = df_ellipse, x = ~x, y = ~ y) %>%
group_by(Cluster) %>%
layer_paths(x= ~x, y= ~y, stroke = ~Cluster, strokeWidth := 1)
myEllPlot
但是当我想在同一个图上绘制 2 层时:
myFullPlot <- ggvis(data = df_ellipse, x = ~x, y = ~ y) %>%
layer_paths(x= ~x, y= ~y, stroke = ~Cluster, strokeWidth := 1) %>%
layer_points(x = ~Axis1, y= ~Axis2, size := 15, fill= ~Cluster, data = ggDF) %>%
add_tooltip(all_values, "hover")
myFullPlot
椭圆没有分组,所以颜色不合适,椭圆没有分开。如果我尝试对我的椭圆进行分组,它不起作用:group_by 只有 layer_paths 需要,它会弄乱 layer_points。
知道如何进行这项工作吗?很抱歉这篇很长的帖子,但我已经尝试了几个小时来完成这项工作:/