简体   繁体   English

使用 ggplot2 创建多个折线图

[英]Use ggplot2 to create multiple line graphs

I have data that looks something like this (except with 90-ish rows).我的数据看起来像这样(90 行除外)。

test <- data.frame("Site_No" = c("01370", "01332", "01442"),"0.99" = c(12, 15, 18), "0.98" = c(14, 15, 18), "0.90" = c(7, 22, 30))

I would like to create 3 separate line plots using ggplot2.我想使用 ggplot2 创建 3 个单独的线图。 The x-axis would be 0.99, 0.98, 0.90 (aka the column names of my data frame). x 轴将是 0.99、0.98、0.90(也就是我的数据框的列名)。 The y-axis would be the range of the values in the columns (so a range from 7 to 30). y 轴将是列中值的范围(因此范围为 7 到 30)。 I would like a plot for each of my Site_No (which are station numbers: 01370, 01332, 01442).我想要一个 plot 用于我的每个 Site_No(站号:01370、01332、01442)。

I am trying my best to figure this out on my own and I'm having no luck because of the structure of my data frame.我正在尽我最大的努力自己解决这个问题,但由于我的数据框的结构,我没有运气。

Thank you for your help!谢谢您的帮助!

I usually use the data.table package and the 'melt' function to get a key-value format.我通常使用 data.table package 和 'melt' function 来获得键值格式。
This format is much better for ggplot2:这种格式对于 ggplot2 来说要好得多:

# Your test data: (notice that i transformed the rownames into a column)
test <- data.frame("0.99" = c(12, 15, 18), "0.98" = c(14, 15, 18), "0.90" = c(7, 22, 30))
test$rownames <- c("01370", "01332", "01442")

# melt and plot:
dt <- data.table::as.data.table(test)

melted <- data.table::melt(dt, measure = c("X0.99","X0.98","X0.90"))

ggplot2::ggplot(data = melted, mapping = aes(x = variable, y = value, group = rownames)) + 
    ggplot2::geom_line() + 
    ggplot2::facet_grid(rows = vars(rownames))

EDIT : based on your edited question:编辑:根据您编辑的问题:

test <- data.frame("Site_No" = c("01370", "01332", "01442"),"0.99" = c(12, 15, 18), "0.98" = c(14, 15, 18), "0.90" = c(7, 22, 30))

dt <- as.data.table(test)

melted <- data.table::melt(dt, measure = c("X0.99","X0.98","X0.90"))

ggplot2::ggplot(data = melted, mapping = aes(x = variable, y = value, group = Site_No)) +
    ggplot2::geom_line() + 
    ggplot2::facet_grid(rows = vars(Site_No))

EDIT2 : Based on your second comment: Create new plots for each group: EDIT2 :根据您的第二条评论:为每个组创建新图:

test <- data.frame("Site_No" = c("01370", "01332", "01442"),"0.99" = c(12, 15, 18), "0.98" = c(14, 15, 18), "0.90" = c(7, 22, 30))

dt <- as.data.table(test)

melted <- data.table::melt(dt, measure = c("X0.99","X0.98","X0.90"))

for (i in unique(melted$Site_No)){
    dev.new()
    print(ggplot2::ggplot(data = melted[Site_No == i,], mapping = aes(x = variable, y = value, group = Site_No)) +
        ggplot2::geom_line())
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM