1

Fairly new to R and wanted to see if this possible. I have the data set below and want to plot x and y on the same line so y continues where x left off at 19 and picks up at 21, with ggplot2.

Would R be able to handle this if i had more columns like, a, b, ect?

enter image description here

Red dots = x Green dots = y

mydata = structure(list(q = 1:7, x = c(12L, 18L, 21L, 19L, 0L, 0L, 0L), 
    y = c(0L, 0L, 0L, 0L, 21L, 25L, 23L)), .Names = c("q", "x", 
"y"), class = "data.frame", row.names = c(NA, -7L))
d.b
  • 32,245
  • 6
  • 36
  • 77
user1901959
  • 35
  • 1
  • 6
  • potential duplicate. http://stackoverflow.com/questions/37034285/graphing-3-axis-accelerometer-data-in-r/37035280#37035280 – Lloyd Christmas Jan 27 '17 at 20:45
  • @Lloyd Christmas. I believe the link was asking the same thing. I search but couldnt find the particular question you linked, I could have been searching for it incorrectly. Thank you. – user1901959 Jan 27 '17 at 22:20

2 Answers2

2

You'd need to reshape your data using the package tidyr and the function gather(ggplot2 likes long data), then remove the points equal to zero.

library(tidyr)
library(ggplot2)

df <- data.frame(q = seq(1:7),
                 x = c(12,18,21,19,0,0,0),
                 y = c(0,0,0,0, 21, 25, 23))

plot_data <- gather(df, variable, value, -q) 

plot_data <- plot_data[plot_data$value != 0,]

ggplot(plot_data, aes(x = q, y = value)) +
  geom_line(color = "black") +
  geom_point(aes(color = variable))

enter image description here

Jake Kaupp
  • 7,892
  • 2
  • 26
  • 36
1

Try this with base R plot:

df <- read.table(text='q x y 
                 1 12 0 
                 2 18 0 
                 3 21 0 
                 4 19 0 
                 5 0 21 
                 6 0 25 
                 7 0 23 ', header=TRUE)

df$y[df$y==0] <- df$x[df$x!=0]
plot(df$q, df$y, pch=19, col=ifelse(df$x==0, 'green', 'red'), xlab='q', ylab='x or y')
lines(df$q, df$y, col='steelblue')

enter image description here

lines(df$q, df$y, col='red')
lines(df$q[df$x==0], df$y[df$x==0], col = 'green')

enter image description here

Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
  • Thank you Sandipan, it works. Going off of your code, if i want the line to change color so that the green dots get a green would line, would I then change it to "lines(df$q, df$y, col = ifelse(d$x==0, 'green', 'red)) – user1901959 Jan 27 '17 at 22:16
  • Thank you Sandipan that looks great – user1901959 Jan 30 '17 at 18:04