ajestudillo
ajestudillo

Reputation: 43

Sorting data on x-axis taking one variable as reference

Hello I think that this must be something stupid, but I am stuck..

I have 5 participants and two task

participant<-1:5
scoreA<- c(20, 18, 19, 15,16)
scoreB<- c(4, 2, 6, 1,3)

I create a data frame and I sort it using the variable scoreA as reference

total<- data.frame(scoreA, scoreB, participant)
total <- total[order(total[,1]),]

Because I want to create a graph line using ggplot I melt the data and try to do the graph:

totalM <- melt(total, id="participant", measured= c("scoreA", scoreB))
ggplot(totalM, aes(participant, value, shape= variable, linetype=variable))+geom_point(size=5)+geom_line(size=1)

I don't understand the reason why I don't see in the graph the data sorted using the variable scoreA as reference. Any idea? How can I do this?

Upvotes: 1

Views: 269

Answers (1)

ialm
ialm

Reputation: 8727

Did you want something like this?

enter image description here

# Convert participant to a factor, with order given by the scoreA variable
# from your "total" data frame
totalM$participant <- factor(totalM$participant,
                             levels=arrange(total, scoreA)$participant)

# Plot!
ggplot(totalM, aes(participant, value, shape= variable, linetype=variable)) +
  geom_point(size=5)+
  geom_line(aes(x=as.numeric(participant)), size=1)
# Note the last geom, I modified the aes

Basically, I make the participant variable a factor, ordered by scoreA. Then ggplot will plot the participant variable in the given factor order. One little adjustment I had to make to force ggplot to plot the lines is to grab the numeric value of the factor for the participant variable for geom_line.

This is the first thing that came to mind. Maybe there is a better way to do this?

Upvotes: 1

Related Questions