简体   繁体   中英

Combining data from different data.frames in ggplot2 with unexpected results

Suppose we have the following data.frames:

dt1 <- data.frame(x=1:10,y=rnorm(10),g="a",c=1)
dt2 <- data.frame(x=1:10,y=rnorm(10),g="b",c=2)
dt <- rbind(dt1,dt2)

bb <- data.frame(x=1:4,y=rep(-5,4))

The following works

qplot(x=x,y=y,data=dt,group=g,colour=c)+geom_line(aes(x=bb$x,y=bb$y),colour="black")

producing additional black line with data from data.frame bb . But with

bb <- data.frame(x=1:6,y=rep(-5,6))

the same plotting code fails with a complaint that number of rows is different. I could merge the data.frames, ie expand bb with NAs, but I thought that the code above is valid ggplot2 code, albeit not exactly in spirit of it. So the question is why it fails? (The answer is probably related to the fact that 4 divides 20, when 6 does not, but more context would be desirable)

The code does not work for me with your first definition of bb too (ggplot2_0.9.2.1):

Error: Aesthetics must either be length one, or the same length as the dataProblems:bb$x, bb$y

This works:

p1 <- ggplot(data=dt,aes(x=x,y=y,group=g,colour=factor(c)))+geom_line()
p1 + geom_line(data=bb,aes(group=0,colour=factor(0))) +
      scale_colour_manual(values = c("black","blue","red"))

You can specify different data sets to use in different layers:

qplot(x=x,y=y,data=dt,group=g,colour=c) + 
  geom_line(aes(x=x, y=y, group=NULL, colour=NULL), data=bb, colour="black")

Here, geom_line uses the data from bb rather than dt . Instead of using a mixture of qplot and geom specifications, here it is in pure ggplot notation:

ggplot(data = dt, aes(x = x, y = y)) +
  geom_point(aes(group = g, colour = c)) +
  geom_line(data=bb, colour="black")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM