r - 从单个图像中的单个数据帧绘制许多线图

标签 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 轴上具有 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"))

最佳答案

使用您的第一个给定数据尝试一下

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

关于r - 从单个图像中的单个数据帧绘制许多线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51085425/

相关文章:

r - ggplot 黄土线从一个数据集到另一个散点图

r - 使用R Shiny框架的密码字段

r - PCA分析中不同类型的椭圆

r - 如何在独立层的ggplot中缩放颜色?

r - ggplot2错误: scale_x_date Showing/Not Dropping Data Outside Specified Limits

r - grid.layout 不喜欢尊重和复合单位

r - R-ggplot-stat_contour无法生成轮廓线

r - R 中的属性值频率(分类变量中的异常值)

r - 在 R 中按日期选择子集

R 语言函数工厂 : How to ensure safety?