R:在一行上绘制两个数据集

时间:2017-01-27 19:46:48

标签: r ggplot2

R相当新,想看看这是否可行。我有下面的数据集,并且想要在同一行上绘制xy,因此y继续在x处于19处离开,在21处拾取ggplot2

如果我有更多列,例如a,b,ect?

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

使用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