2017-01-27 93 views
1

相當新的R,並希望看看這是否可能。我有下面的數據集,並且想要在同一條線上繪製xy,所以y繼續,其中x從19開始並在21開始,ggplot2R:繪製兩條數據集在一條線上

如果我有更多的列,如a,b等,R能夠處理這個問題嗎?

enter image description here

紅點= x 綠點= 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)) 
+0

潛在d uplicate。 http://stackoverflow.com/questions/37034285/graphing-3-axis-accelerometer-data-in-r/37035280#37035280 –

+0

@勞埃德聖誕節。我相信鏈接問的是同樣的事情。我搜索,但無法找到您鏈接的特定問題,我可能一直在錯誤地搜索它。謝謝。 – user1901959

回答

1

base R情節試試這個:

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

+0

謝謝Sandipan,它的工作原理。 如果我想讓線條改變顏色,讓綠點變成綠線,那麼我會將它改爲「線條(df $ q,df $ y,col = ifelse(d $ x == 0,'green','red)) – user1901959

+0

謝謝Sandipan,看起來很棒 – user1901959

2

您將需要使用包tidyr和功能gatherggplot2喜歡長的數據),以重塑你的數據,然後刪除點數等於零。

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

+0

謝謝傑克。使用ggplot知道如何做到這一點真棒 – user1901959