I have data that looks something like this (except with 90-ish rows).
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. The x-axis would be 0.99, 0.98, 0.90 (aka the column names of my data frame). The y-axis would be the range of the values in the columns (so a range from 7 to 30). I would like a plot for each of my Site_No (which are station numbers: 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.
This format is much better for 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:
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())
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.