在单个图像中从单个数据帧绘制许多折线图

时间:2018-06-28 14:28:18

标签: r ggplot2

我具有以下形式的数据框:

Frequency Distance Value
10        10       2
10        20       4
10        30       6
20        10       4
20        20       5
20        30       5
30        10       2
30        20       4
30        30       2

我想创建一个在x轴上具有Distance在y axix上具有Value的绘图。我还想绘制多个图,每个频率绘制一个图。如下图所示:

Sample plot

如何获得此结果?

到目前为止,通过阅读其他答复,我已经完成了此操作,但是我只能绘制一行(我在创建xymelt变量时指定的行:

# Load required libraries
require(ggplot2)
require(reshape2)

# Function for importing a file and remove useless columns
loadCSVFile <- function(f) {
  csv = read.csv(f, header = TRUE);
  # other code for removing useless columns
  return(csv);
}

# Load and concatenate all .csv files from current working dir
files = list.files(pattern="*.csv");
myfiles = do.call(rbind, lapply(files, loadCSVFile))

# Plot. Problem here. I'm trying to use split and melt.
out <- split( myfiles , f = myfiles$Frequency)
xymelt <- melt(out$`40`, id.vars = 'Distance')
ggplot(xymelt, aes(x = Dist, y = value, color = variable)) + theme_bw() + geom_line();

编辑:

dput(out)的示例:

structure(list(`20` = structure(list(Frequency = c(20L, 20L, 20L, 
20L), Distance = c(10L, 20L, 30L, 40L), Value = c(97.946, 111.042, 
119.437, 125.908)), .Names = c("Frequency", "Distance", "Value"), row.names = c(NA, 
4L), class = "data.frame"), `40` = structure(list(Frequency = c(40L, 
40L, 40L, 40L), Distance = c(10L, 20L, 30L, 40L), Value = c(97.937, 
111.058, 119.621, 126.318)), .Names = c("Frequency", "Distance", "Value"
), row.names = 5:8, class = "data.frame"), `60` = structure(list(
    Frequency = c(60L, 60L, 60L, 60L), Distance = c(10L, 20L, 30L, 
    40L), Value = c(97.9015, 111.045, 119.802, 126.765)), .Names = c("Frequency", 
"Distance", "Value"), row.names = 9:12, class = "data.frame")), .Names = c("20", 
"40", "60"))

1 个答案:

答案 0 :(得分:2)

只需使用您的第一个给定数据

library(tidyverse)
read.table(text="Frequency Distance Value
10        10       2
           10        20       4
           10        30       6
           20        10       4
           20        20       5
           20        30       5
           30        10       2
           30        20       4
           30        30       2", header=T) %>% 
ggplot(aes(Distance, Value, color=factor(Frequency))) + 
   geom_line()

enter image description here

使用您的dput示例,您可以尝试

d %>% 
  bind_rows() %>%  
  ggplot(aes(Dist, RefAtt, color=factor(FreqMhz))) +
    geom_line()