-1

I have a data set with 6 alternatives. I used the scale function to standardize my data set. Now I want to plot a curve for each row.

I want to have my six alternatives as values in the X-Axis, and their standardize value in the Y-Axis.

A sample of my data set is like this:

    fish   rice   meet   milk

   1   2.3    3.4   1.4     1.3
   1   2.6    3.5   2.4     2.4
   1   4.3    1.9   3.3     3.1
   1  1.3    2.4   4.4     9.3
   2  1.3    3.4   4.1     3.4
   2   3.3    2.9   3.3     2.1
   2   4.5    3.9   3.3     3.1
   2  1.4    2.4   4.4     9.3

where first column is individual, in this sample we had 2 person Now I want to draw a curve for each row so in the x-axis I have (fish, rice meet milk) and in y-axis I have these numbers.

For example, the first curve is formed by connecting points 2.3, 3.4, 1.4, 1.3 in y-axis

1 Answers1

2

Since you want each row to be a separate group, you should make row number a variable to preserve that information, then reshape the data from wide to long so you can plot it properly in ggplot2:

library(tidyverse)

df1 = df %>%
    rowid_to_column('row') %>%
    gather(key, value, -row)

head(df1)
  row  key value
1   1 fish   2.3
2   2 fish   2.6
3   3 fish   4.3
4   4 fish   1.3
5   1 rice   3.4
6   2 rice   3.5

# group is needed to tell ggplot which points to connect in each line

ggplot(df1, aes(x = key, y = value, color = factor(row), group = row))  +
    geom_line()

enter image description here

divibisan
  • 11,659
  • 11
  • 40
  • 58
  • I got an error : Error in TravelMode1 %>% rowid_to_column("row") %>% gather(key, value, : could not find function "%>%" –  Jun 04 '19 at 16:38
  • Did you properly load the tidyverse packages? `%>%` is in `dplyr` which will be loaded by `library(tidyverse)` – divibisan Jun 04 '19 at 16:40
  • Did they load correctly? That error means that `dplyr` wasn't attached properly. Try `library(dplyr)` and make sure it _actually_ attached without errors – divibisan Jun 04 '19 at 16:45
  • Try restarting R and reinstalling the packages. – divibisan Jun 04 '19 at 16:53