简体   繁体   中英

Error ploting data.frames with different length with ggplot2

I am trying to plot two data.frames with different length using ggplot2 with the following code:

require(ggplot2)

shortda <- data.frame(SST=seq(1:30),chla=rlnorm(30),year=rep(2001:2010,each=3))
longda  <- data.frame(SST=seq(1:300),pred=rlnorm(300))

ggplot(shortda, aes(x=SST, y=chla, colour=year))+ geom_point()

ggplot(shortda, aes(x=SST, y=chla, colour=year))+ geom_point() + geom_line(data=longda,aes(SST,pred))

the first plot with one data.frame works well, but the second gives an error:

Error in eval(expr, envir, enclos) : object 'year' not found

what I am doing wrong?

My sessinInfo is

sessionInfo()
R version 3.3.3 (2017-03-06)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 14.04.5 LTS

locale:
  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=es_AR.UTF-8       
[4] LC_COLLATE=en_US.UTF-8     LC_MONETARY=es_AR.UTF-8    LC_MESSAGES=en_US.UTF-8   
[7] LC_PAPER=es_AR.UTF-8       LC_NAME=C                  LC_ADDRESS=C              
[10] LC_TELEPHONE=C             LC_MEASUREMENT=es_AR.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
  [1] stats     graphics  grDevices datasets  utils     methods   base     

other attached packages:
  [1] ggplot2_2.1.0

loaded via a namespace (and not attached):
  [1] labeling_0.3     colorspace_1.2-6 scales_0.4.1     plyr_1.8.3       tools_3.3.3      gtable_0.2.0    
[7] Rcpp_0.12.4      grid_3.3.3       digest_0.6.9     munsell_0.4.3   

You could not put any data in the ggplot statement. Would something like this give you the desired result?

ggplot()+ geom_point(data=shortda, aes(x=SST, y=chla, colour=year)) + 
          geom_line(data=longda,aes(SST,pred))

在此处输入图片说明

ggplot wants to color your lines by year , but it can't find it in longda .

You can use eg:

geom_line(aes(y = pred), longda, col = 1)

or

geom_line(aes(y = pred, col = NULL), longda)

to indicate that your color mapping should not apply to the lines.

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