【问题标题】:loop for ggplot2 formula in rr中的ggplot2公式循环
【发布时间】:2012-07-20 00:35:55
【问题描述】:

这是一个例子:

require(ggplot2)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()

yintercept <- c(5, 12, 20, 28, 29, 40)
col <- c("red", "blue", "green", "pink", "yellow", "tan")

# for the first level yintercept, and col 
p + geom_hline(aes(yintercept = 5), col = "red")

我有上面列出的更多级别的变量,而不是写长的“+”公式,我可以循环这个过程吗?对不起,简单的问题。

编辑:如何循环公式中的 x 或 y 变量

   myd <- data.frame (y = rnorm (100, 5, 10), X1 = rnorm (100, 5, 1), 
    X3 = rnorm (100, 10, 2), X4 = rnorm (100, 50,4))

x <- c("X1",  "X2",   "X3", "X4")

p <- ggplot(myd, aes(y = y)) + 
 mapply ( function (x) (geom_point(x = aes_string (x))))

【问题讨论】:

    标签: r loops ggplot2


    【解决方案1】:

    ggplot2 方法是始终将数据放入数据框中并映射美学。它使事情变得更简单:

    df <- data.frame(yint = yintercept)
    
    # for the first level yintercept, and col 
    p + geom_hline(data = df,aes(yintercept=yint,colour = factor(yint))) + 
        scale_colour_manual(values = col,guide = "none")
    

    【讨论】:

    • 感谢您的出色回答,我仍然有疑问 x 或 y aes 的名称是否仍可以与颜色或截取相同的循环...查看我最近的编辑
    • 原则上可以完成这种事情,尽管可能不是您所描绘的方式。但是,这通常不是处理事情的 方式(至少对于您提供的示例而言不是)。唯一的例外是,如果在数据框中或多或少不可能安排您的数据,但您没有提供这种情况的示例。
    【解决方案2】:

    试试

    p+mapply(function(a,b){dum<-aes_string(yintercept=a);
                           geom_hline(dum, col = b)},a=yintercept,b=col)
    

    【讨论】:

    • 你不需要分号。
    猜你喜欢
    • 1970-01-01
    • 2022-08-18
    • 2015-05-12
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多