user1901959
user1901959

Reputation: 35

R: Plot two data set on one line

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))

Upvotes: 1

Views: 74

Answers (2)

Sandipan Dey
Sandipan Dey

Reputation: 23109

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

Upvotes: 1

Jake Kaupp
Jake Kaupp

Reputation: 8072

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

Upvotes: 2

Related Questions