YellowPillow YellowPillow - 1 month ago 15
R Question

How to add points (which are classes) on top of a ggplot that already has it's x,y axis set

So I want to plot the prediction (which are my classes) in conjunction with some various inputs. Here is what I have tried:

# First get the data
sitting.flexion.data <- all.data[10:5009,]
prediction <- data.frame(pred[1:5000])
prediction$index <- 1:5000
colnames(prediction) <- c("Body.Orientation", "index")
sitting.flexion.data$index <- 1:nrow(sitting.flexion.data)
sitting.flexion.data$Event <- as.factor(sitting.flexion.data$Event)

# As we are plotting many lines we need to use tidyr to melt the data
sitting.flexion.data <- gather(sitting.flexion.data, key, value,
Back.Pelvis.F.E,Back.Pelvis.LF, Back.Trunk.F.E, Back.Trunk.LF,
Back.Lumbar.F.E, Back.Lumbar.LF)

# Now plot the graph
p1 <- ggplot(sitting.flexion.data, aes(x = index, y = value, color = key))
p2 <- p1 + geom_line()
p2


This gives me:
enter image description here
Which is good because it shows the values of these inputs, but now what I want to do is to plot the class that is predicted by the model given these inputs. So for each index there will be a class associated with it.

This is what I have tried:

p3 <- p2 + geom_point(data = prediction, aes(x = index, y = Body.Orientation))


Which gives me this error:
Error in data.frame(x = 1:5000, y = c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,: arguments imply differing number of rows: 5000, 0


And I have no idea how to solve it as:
dim(prediction) = 5000 2
which means that they should have the same number of rows right?

The closest that I have got is by first plotting the predicted class than the inputs:

p4 <- ggplot(prediction, aes(x = index, y = Body.Orientation))
p4 + geom_point() + geom_line(data = sitting.flexion.data, aes(x=index, y= value, color = key))


Which gives me:
enter image description here

Which is nearly what I want but I don't want the y-axis to be the class that is predicted, I want the y-axis of the first graph which are the values of the inputs. I've been at this for hours, and I can't seem to find a fix, any ideas?

Here is a rough drawing of what I want, the value of the input are in degrees:

enter image description here

P.S. sorry for the tiny labels for the graphs

Answer

Starting from p2which gave you the first plot. I would add +geom_point(data=prediction, aes(x=index,y=rep(-40,5000),colour=Body.Orientation).
Since you want the data to be on a line, I set y to a given value, here -40 and give it the same length as x.
Let me know if it works. If it doesn't please consider providing some sample data to make this reproducible.