使用ggplot2来表示散点图中每个点的小饼图

使用ggplot2来表示散点图中每个点的小饼图

问题描述:

我想创建一个散点图,其中每个点都是一个小饼图。例如考虑以下数据:使用ggplot2来表示散点图中每个点的小饼图

foo <- data.frame(X=runif(30), Y=runif(30),A=runif(30),B=runif(30),C=runif(30)) 

下面的代码将散点图,表示每个点的XY值:

library(reshape2) 
library(ggplot2) 
foo.m <- melt(foo, id.vars=c("X","Y")) 
ggplot(foo.m, aes(X,Y))+geom_point() 

enter image description here

以下代码将使每个点的饼图:

p <- ggplot(foo.m, aes(variable,value,fill=variable)) + geom_bar(stat="identity") 
p + coord_polar() + facet_wrap(~X+Y,,ncol=6) + theme_bw() 

enter image description here

但我正在寻找合并它们:创建一个散点图,其中每个点被替换为饼图。这样我就可以在同一个图表中显示每条记录的所有5个值(X,Y,A,B,C)。

有没有办法做到这一点?

+4

天哪。我希望不是。 – hrbrmstr 2014-10-26 21:31:44

+0

@hrbrmstr为什么?我抽取了一些观点,X和Y来自主成分分析(PCA)。 A,B和C是每个记录的属性(实际上他们是6,而不是3)。你有更好的想法在PCA阴谋中显示它们吗? – Ali 2014-10-26 21:47:23

+0

条形图>饼图。总是。 – hrbrmstr 2014-10-27 01:00:06

这是你可以用包ggsubplot做的事情。不幸的是,根据问题#10 here,这个软件包不适用于R 3.1.1。如果我使用旧版本的R(3.0.3),我成功地运行了它。

使用你的长期数据集,你可以把巴图在每个XY点是这样的:

library(ggplot2) 
library(ggsubplot) 

ggplot(foo.m) + 
    geom_subplot2d(aes(x = X, y = Y, 
        subplot = geom_bar(aes(variable, value, fill = variable), stat = "identity")), 
       width = rel(.5), ref = NULL) 

enter image description here

这使基本的想法,虽然还有许多其他选项(如控制当情节空间中存在重叠时,子情节向哪里移动)。

This answer有更新的R版本的ggsubplot的更多信息。

+0

谢谢。我有R 3.1.1,正如你所说的那样会导致错误。你能否在答案中添加你的情节的快照? – Ali 2014-11-26 03:09:13

+1

@Ali我用一个例子更新了答案。 – aosmith 2014-11-26 16:10:49