I have a sample data given below with sample IDs which are unique, and 3 groups. I need to plot all the observations (rows) in 'df' but color them according to the group IDs ('groupid'). Here's what I have so far:
# sample data creation
samples <- paste0("S",c(1:9))
groupid <- c("group1", "group2", "group3")
foo <- data.frame(Samples = samples, Group = rep(groupid, each = 3))
bar <- data.frame()
for(i in 1:length(samples)){
ran.data <- rnorm(10, 0.5)
#colnames <- paste0("w",c(1:length(ran.data)))
for(j in 1:length(ran.data)){
bar[i,j] <- ran.data[j]
}
}
df <- cbind(foo, bar)
# ******************
# creating plot data
plotdf <- as.data.frame(t(df))
cols <- as.character(unlist(plotdf[1,]))
plotdf <- plotdf[-c(1,2),] # removing rows
groupid <- df$Group # var to group by
names(plotdf) <- cols
plotdfrows <- names(df[,3:ncol(df)])
plotdf$rownames <- plotdfrows
# melt and plot
library(reshape2)
library(ggplot2)
melteddf <- melt(plotdf, id.var = "rownames")
final.plot <- ggplot(melteddf, aes(rownames, value, colour = variable, group = groupid)) + geom_point() + #geom_line() +
scale_y_discrete(breaks=seq(-3, 3, by = 0.5)) + scale_x_discrete() +
labs(title = paste("Sample plot")) #breaks=seq(0, 4, by = 0.5)
print(final.plot)
When I use group = 1, I manage to get the plot but observations are colored differently. But where can I specify the 'groupid' information? Thanks in advance.