2012-07-11 65 views
2

我正在处理堆积条形图,但是我需要在此处为​​特定堆栈分配图像。如何将图片分配到堆积条形图

enter image description here

enter image description here

我怎样才能做到这一点R.

DF = data.frame(names = c("tomato", "potato", "cabbage", 
          "sukuma-wiki", "terere"), 
       freq=c(7,4,5,8,20)) 
barplot(as.matrix(DF[,2]), col=heat.colors(length(DF[,2])), 
     legend=DF[,1], xlim=c(0,9), width=2) 

enter image description here

+2

我会用ggplot2来解决这个问题,虽然base也是可行的。这里有一个更新手册:[(LINK)](http://cloud.github.com/downloads/hadley/ggplot2/guide-col.pdf)。请参阅第22-23页 – 2012-07-11 05:03:14

+0

但是在此,图像的位置需要手动设置。我需要在每个绘图的输入文件中以不同的手位置动态地生成100,000个图。我该怎么做? – Manish 2012-07-11 07:17:14

回答

1

这是一种方式,你可以如何与grid做到这一点。

# libraries 
library(jpeg) 
library(grid) 

# a is your image 
a <- readJPG("foo.jpg") 

# ypos.img is at which height of the barchart you want to place the image 
ypos.img <- 10 

# Create a new polot 
grid.newpage() 
pushViewport(viewport(width=0.9, height=0.9)) 

# add image 
pushViewport(viewport(yscale=c(0,sum(DF[,2])), xscale=c(0,1), x=0, y=0, width=0.4, height=1, just=c("left", "bottom"))) 
grid.raster(a, y=unit(ypos.img, "native")) 

# add barplot 
popViewport() 
pushViewport(viewport(x=0.4, y=0, width=0.6, height=1, just=c("left", "bottom"))) 
pushViewport(dataViewport(xscale=c(0,2), yscale=c(0, sum(DF[,2])))) 
cols <- heat.colors(length(DF[,2])) 

for (i in 1:nrow(DF)) { 
start <- 0 
if (i > 1) start <- sum(DF[1:(i-1), 2]) 
grid.rect(x=0, y=start, width=1, height=DF[i, 2], default.units="native", just=c("left", "bottom"), gp=gpar(fill=cols[i])) 
} 

popViewport(2) 

# Legend 
pushViewport(viewport(x=0.75, y=0, width=0.25, height=1, just=c("left", "bottom"))) 
ypos <- 0.8 
for (i in 1:nrow(DF)) { 
grid.rect(x=0.05, y=ypos, width=0.1, height=0.05, just=c("left", "bottom"), gp=gpar(fill=cols[i])) 
grid.text(DF[i,1], x=0.2, y=ypos, just=c("left", "bottom")) 
ypos <- ypos - 0.05 
} 

popViewport() 
+0

感谢它对我来说工作正常。 – Manish 2012-07-12 01:16:13

+0

感谢它对我来说工作正常。有没有什么方法可以根据颜色值来表示颜色强度。我的意思是热量的颜色强度应该按照(光或暗)的数字值。 – Manish 2012-07-12 03:32:08

+0

查看'?gpar',然后可以调整'alpha'值。如果它适合您,请考虑将问题标记为已回答。 – johannes 2012-07-12 06:58:45