r - 在 r 中循环 ggplot2 公式

标签 r loops ggplot2

下面是一个例子:

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))))

最佳答案

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")

关于r - 在 r 中循环 ggplot2 公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571305/

相关文章:

r - Rstudio 中的 %>% 键绑定(bind)/键盘快捷键

java - 输入并指定要打印的字符以及每行要打印的字符数

r - 当从两个数据框构建绘图时有两个图例

r - ggplot2 在 .elements_tree 之外创建一个新的主题元素

r - 使用缺少绘图的数据标签文本大小

r - R 中的烤宽面条图

R 脚本 - NLS 不工作

java - 如何在数组列表中查找对象?

r - 解码 R 中的函数

android - 在 android 中,我怎样才能创建一个先等待 Action 继续的循环?