Hello Everyone,
I have a big issue trying to print out all of the data points in RStudio using ggplot().
I first got a matrix and converted it into a data frame like this (I upload a picture of the data frame in this question).......
Afterwards, I want to try to plot all of the values in every column using ggplot() and include a legend in the plot with the names of all the columns. In ggplot, I know you could plot only one column as the y-axis using ggplot(). I would like to know if there is any way in which I could include all of the values in every column as the y-axis values and include the row names in the data frame as the x-axis in the same graph. If you need more information for this problem, I am more than happy to be more specific. Thank you!
I do not know what your data look like, so I invented some.
I would reshape the data so the column names become one column and the values are in one column.
I used several print statements in the code to show how the data change during the process.
#Invent some data
DF <- data.frame(AA = 1:4, BB = 2:5, CC = 3:6, DD = 4:7)
row.names(DF) = c("alpha", "beta", "gamma", "delta")
DF
#> AA BB CC DD
#> alpha 1 2 3 4
#> beta 2 3 4 5
#> gamma 3 4 5 6
#> delta 4 5 6 7
library(tibble)
library(ggplot2)
library(tidyr)
DF <- rownames_to_column(DF, var = "Xval")
DF
#> Xval AA BB CC DD
#> 1 alpha 1 2 3 4
#> 2 beta 2 3 4 5
#> 3 gamma 3 4 5 6
#> 4 delta 4 5 6 7
DF <- DF %>% pivot_longer(cols = AA:DD, names_to = "Source", values_to = "Value")
DF
#> # A tibble: 16 x 3
#> Xval Source Value
#> <chr> <chr> <int>
#> 1 alpha AA 1
#> 2 alpha BB 2
#> 3 alpha CC 3
#> 4 alpha DD 4
#> 5 beta AA 2
#> 6 beta BB 3
#> 7 beta CC 4
#> 8 beta DD 5
#> 9 gamma AA 3
#> 10 gamma BB 4
#> 11 gamma CC 5
#> 12 gamma DD 6
#> 13 delta AA 4
#> 14 delta BB 5
#> 15 delta CC 6
#> 16 delta DD 7
#Set the order of the Xval values if you do not want them in alphabetical order
DF$Xval <- factor(DF$Xval, levels = c("alpha", "beta", "gamma", "delta"))
ggplot(DF, aes(Xval, Value, color = Source, group = Source)) +
geom_point() + geom_line()