在ggplot2中使用字符串值作为变量

时间:2013-09-12 13:16:53

标签: r ggplot2

我想通过变量xAxis和split

来控制以下图
library(ggplot2)
data <- data.frame(
  col1 = c(1, 2, 2, 3, 3, 4),
  col2 = c(1, 1, 2, 1, 2, 1),
  z = rnorm(6))

xAxis="col1"
split="col2"

以下示例确实有效

df<-split(data, data[,xAxis])
p1 <- ggplot()
for(i in df){
 p1 <- p1 + geom_bar(data = i, aes(x=col1, y = ..count..), fill = "blue", alpha = 0.2)
}
p1

df<-split(data, data[,xAxis])
p1 <- ggplot()
for(i in df){
 p1 <- p1 + geom_bar(data = i, aes(x=i[,xAxis], y = ..count..), fill = "blue", alpha = 0.2)
}
p1

不起作用。还有一些其他数据,但我得到的第二个数据完全相同,例如错误:

Error in data.frame(x = list(sec = c(40, 18, 5, 47, 50, 7, 9, 22, 27,  : 
  Argument used differnt number of rows: 707, 3938

0 个答案:

没有答案