5

I ham fairly new to R and I might have a rather "stupid question" here.

I have a data frame that consists multiple measurements of 10 sensors (named X1,X2,...X10). Each row number indicates the the trial number. So for example if we assume we have 7 trials then the data frame looks something like this:

    X1  X2  X3  X4  X5  X6  X7  X8  X9  X10
1   5   2   6   0   10  10  3   1   8   9
2   1   2   2   10  1   0   8   2   5   5
3   9   0   0   8   7   9   10  3   3   5
4   10  9   5   6   7   9   0   9   8   6
5   1   4   2   4   3   10  8   0   1   7
6   5   2   10  7   6   0   4   1   8   7
7   10  2   2   1   4   3   2   4   6   2

I want to plot all the rows together. For example for the first trial x will be 1:10 and y is the first row of the data frame.

I know some ways to do this but how can I use ggplot to do this ? Thanks

Sepehr
  • 442
  • 1
  • 6
  • 17

1 Answers1

12

What you need to do is restructure the dataframe into a long format. There are many ways to do it. A quick one could be to use reshape2 package e.g.

Your data:

df <- read.table(text="    X1  X2  X3  X4  X5  X6  X7  X8  X9  X10
1   5   2   6   0   10  10  3   1   8   9
2   1   2   2   10  1   0   8   2   5   5
3   9   0   0   8   7   9   10  3   3   5
4   10  9   5   6   7   9   0   9   8   6
5   1   4   2   4   3   10  8   0   1   7
6   5   2   10  7   6   0   4   1   8   7
7   10  2   2   1   4   3   2   4   6   2", header=T)


library(reshape2)
df <- melt(df)  #the function melt reshapes it from wide to long
df$rowid <- 1:7  #add a rowid identifying variable

your dataframe now looks like this:

head(df, 10)

#   variable value rowid
#1        X1     5     1
#2        X1     1     2
#3        X1     9     3
#4        X1    10     4
#5        X1     1     5
#6        X1     5     6
#7        X1    10     7
#8        X2     2     1
#9        X2     2     2
#10       X2     0     3

Then you can plot this

library(ggplot2)

A scatter plot:

ggplot(df, aes(variable, value, group=factor(rowid))) + geom_point(aes(color=factor(rowid)))

A line graph:

ggplot(df, aes(variable, value, group=factor(rowid))) + geom_line(aes(color=factor(rowid)))

variable is your x-axis, value is your y-axis. I've made the variable 'rowid' a factor and we color by this factor also

Looks like this:

enter image description here

You can then play around with ggplot themes to make it look much nicer.

jalapic
  • 13,792
  • 8
  • 57
  • 87
  • 1
    Thanks Jalapic. How can I plot X1 vs X2 (like a scatterplot of the two types of variables plotted against each other on the axes)? – AHegde Jun 08 '16 at 20:59
  • @jalapic What if you wanted to go the other way? All my rows are named, and I have one column of sums. – Travis Heeter Oct 08 '16 at 19:40
  • Don't you need to do "df$rowid <- 1:7" first? I'm doing something similar with tidyr's pivot_longer. – gghuffer Aug 30 '23 at 16:00