YellowPillow YellowPillow - 1 year ago 65
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 <-[10:5009,]
prediction <- data.frame(pred[1:5000])
prediction$index <- 1:5000
colnames(prediction) <- c("Body.Orientation", "index")$index <- 1:nrow($Event <- as.factor($Event)

# As we are plotting many lines we need to use tidyr to melt the data <- gather(, 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(, aes(x = index, y = value, color = key))
p2 <- p1 + geom_line()

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 =, 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download