2012-10-15 43 views
4

我想绘制列表中的元素,特别是根据它所属的类对每个点着色,使用外部列表索引作为ax值和每个值的值内部列表的元素作为ay值。一个示例列表,以2子列表:从多种颜色的列表列表中绘制元素

sample.list <- list(list("A"=0,"B"=0.14285, "C"=0.75), list("A"=0.138,"B"=0,"C"=0.1)) 
[[1]] 
[[1]]$A 
[1] 0 

[[1]]$B 
[1] 0.14285 

[[1]]$C 
[1] 0.75 

[[2]] 
[[2]]$A 
[1] 0.138 

[[2]]$B 
[1] 0 

[[2]]$C 
[1] 0.1 

我的期望的输出将在点

(1, 0), (1, 0.14285), (1, 0.5)

(即,子列表元件形成沿x=1的垂直线)和第二绘制第一子列表子列表将被类似地绘制。此外,每个子列表元素将具有不同的颜色 - A可能是红色的,B绿色等。只是为了澄清,我试图在一张图上完成这一切。此外,列表元素的数量可能会根据数据集而变化。任何关于如何解决这个问题的指针都非常感谢!

回答

3
library(plyr) 
library(ggplot2) 
library(reshape2) 
df <- melt(ldply(sample.list, data.frame)) 
df2 <- ddply(df, .(variable), function(x) { x$index <- 1:nrow(x); x}) 
ggplot(df2, aes(index, value, color = variable)) + 
geom_point(size=3) + scale_x_continuous(breaks = seq(1:max(df2$index))) 

enter image description here

+0

这几乎是它!但是,我试图做的是将每个子列表作为一组y值,其x值是外部列表索引。所以在你的情节中,会有x个坐标,每个坐标都有3个点。发帖后发现我的错误 – learner

+0

。这个版本怎么样? – Maiasaura

+0

这很完美。我总是惊讶于有多少R需要学习。谢谢! – learner

1

下面是对于那些非ggplot-ERS底液:

plot(1:length(sample.list),ylim=c(0,max(unlist(sample.list))),xaxt="n",ann=FALSE) 
axis(1,at=1:length(sample.list),labels=1:length(sample.list)) 

invisible(
    sapply(
     1:length(sample.list), 
     function(x) { 
     tmp2plot <- sample.list[[x]] 
     points(rep(x,length(tmp2plot)),unlist(tmp2plot),col=1:length(tmp2plot),pch=19) 
     } 
) 
) 

title(xlab="Index",ylab="Value") 

结果:

enter image description here