2017-01-27 55 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