簡體   English   中英

使用 ggplot2 創建多個折線圖

[英]Use ggplot2 to create multiple line graphs

我的數據看起來像這樣(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))

我想使用 ggplot2 創建 3 個單獨的線圖。 x 軸將是 0.99、0.98、0.90(也就是我的數據框的列名)。 y 軸將是列中值的范圍(因此范圍為 7 到 30)。 我想要一個 plot 用於我的每個 Site_No(站號:01370、01332、01442)。

我正在盡我最大的努力自己解決這個問題,但由於我的數據框的結構,我沒有運氣。

謝謝您的幫助!

我通常使用 data.table package 和 'melt' function 來獲得鍵值格式。
這種格式對於 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))

編輯:根據您編輯的問題:

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 :根據您的第二條評論:為每個組創建新圖:

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