SimpleMind SimpleMind - 2 months ago 8
R Question

R plotting values from multiple columns in same axis with ggplot

I have a data frame wherein marks of a person are stored in multiple columns based on the class like this:

Sno. Student Name Class1 Class2 Class3 Class4 Class5 Class6 Class7 Class8
3 1 XX 75 77 80 77 85 87 89 92
4 2 YY 90 90 87 83 80 78 76 75


I would like to plot the all the marks on the x axis and the y axis must be from 1 -100.
- Thanks Sven Hohenstein
I was able to get a solution for it.
But is there another way to solve this problem. your graph is just what I want my output to look like.
But I do have a 10 row 16 column data frame if i am to melt that it would generate a huge dataframe.
If there is way to generate the same plot without melting the data frame it would be much more nicer.

Thank you.

Answer

I am not exactly sure what kind of plot you're looking for. Here is a proposal.

Read the data:

dat <- read.table(text = "Sno.   Student Name Class1 Class2 Class3 Class4 Class5 Class6 Class7 Class8 
3    1         XX     75     77     80     77     85     87     89     92    
4    2         YY     90     90     87     83     80     78     76     75", header = TRUE)

Reshape the data to the long format:

library(reshape2)
dat_m <- melt(dat, id.vars = "Student", 
              measure.vars = grep("^Class", names(dat), value = TRUE))

Create the plot:

library(ggplot2)
ggplot(dat_m, aes(y = value, x = variable, colour = as.factor(Student))) +
      geom_point() +
      geom_line(aes(group = Student)) +
      coord_cartesian(ylim = c(1, 100))

enter image description here