通过循环在ggplot2中设置图层 [英] Set layers in ggplot2 via loop
本文介绍了通过循环在ggplot2中设置图层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望
data <- data.frame(col1 = c(1, 2, 2, 3, 3, 4),
col2 = c(1, 2, 2, 1, 2, 1),
z = rnorm(6))
p1<-ggplot(data, aes(x=col1))
for(idx in unique(data$col2)){
p1<-p1 + geom_bar(subset = .(col2 == idx), aes(y = ..count..),fill = "blue", alpha = 0.2)
}
p1
具有与
p1<-ggplot(data, aes(x=col1))
p1<-p1 + geom_bar(subset = .(col2 == 1), aes(y = ..count..),fill = "blue", alpha = 0.2)
p1<-p1 + geom_bar(subset = .(col2 == 2), aes(y = ..count..),fill = "blue", alpha = 0.2)
p1
但不是.因此,如何在for循环中产生与第二个示例相同的输出.
but it istn't. So how could I produce in the for loop the same output like in the second example.
推荐答案
如果您自己进行子设置,则此问题很简单:
This problem is simple if you do the subsetting yourself:
library(ggplot2)
data <- data.frame(
col1 = c(1, 2, 2, 3, 3, 4),
col2 = c(1, 2, 2, 1, 2, 1),
z = rnorm(6))
ids <- unique(data$col2)
p1 <- ggplot(data, aes(col1, y = ..count..))
for(id in ids){
df <- data[data$col2 == id, ]
p1 <- p1 + geom_bar(data = df, fill = "blue", alpha = 0.2)
}
p1
这篇关于通过循环在ggplot2中设置图层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文