Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用ggplot按名称访问循环中的字段_R_Ggplot2 - Fatal编程技术网

R 使用ggplot按名称访问循环中的字段

R 使用ggplot按名称访问循环中的字段,r,ggplot2,R,Ggplot2,让我们组成一些数据,这是一个噪声正弦: xx <- sort(runif(125, 0, 2 * pi)) yy <- sin(xx) + rnorm(length(xx), sd = 0.3) data <- data.frame(x = xx, y = yy) 这有多个问题 但最重要的是,如何用for循环替换最后一部分?例如: p <- ggplot(data) + geom_point(aes(x = x, y = y, color = "samp

让我们组成一些数据,这是一个噪声正弦:

xx <- sort(runif(125, 0, 2 * pi))
yy <- sin(xx) + rnorm(length(xx), sd = 0.3)
data <- data.frame(x = xx, y = yy)
这有多个问题

但最重要的是,如何用for循环替换最后一部分?例如:

p <- ggplot(data) + 
  geom_point(aes(x = x, y = y, color = "samples")) +
  geom_function(fun = sin, aes(x = x, color = "original sine"))

for (f in ff) {
  p <- p + geom_line(aes(x = x, y = f))
}

p

p以长格式获取以
“f”
开头的列,然后绘制:

library(tidyr)
library(ggplot2)

data %>%
  pivot_longer(cols = starts_with('f')) %>%
  ggplot() + geom_point(aes(x = x, y = y, color = "samples")) +
  geom_function(fun = sin, aes(x = x, color = "original sine")) +
  geom_line(aes(x = x, y = value, color = name), linetype = 'dashed')

将宽转换为长,然后打印。是的,这看起来比我的尝试要好;如何用有意义的东西删除/替换“颜色”?此外,图例中未显示线型。您可以添加
+labs(color='legend title')
以包括图例标题。
p <- ggplot(data) + 
  geom_point(aes(x = x, y = y, color = "samples")) +
  geom_function(fun = sin, aes(x = x, color = "original sine"))

for (f in ff) {
  p <- p + geom_line(aes(x = x, y = f))
}

p
library(tidyr)
library(ggplot2)

data %>%
  pivot_longer(cols = starts_with('f')) %>%
  ggplot() + geom_point(aes(x = x, y = y, color = "samples")) +
  geom_function(fun = sin, aes(x = x, color = "original sine")) +
  geom_line(aes(x = x, y = value, color = name), linetype = 'dashed')