[英]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.