Search code examples
rgraph

How to construct two plots one of which has fewer y values than the other in R?


I have a census data of 8 years and their corresponding population values. I have worked through a model and computed the fitted values corresponding to the given years in the data and also estimated the values of the population between the two given years (10 years gap).

I want to plot the fitted values over all the years (census year and non-census year). In that very plot I want to plot the given population observations against the census years.

What would be the best way to approach this problem in R? Any hint or advice would be appreciated.

I have tried to dig in the internet to find any tutorial, unfortunately so far I have failed to come across any that caters to my need.

This is the snippet of the data:

Census Yr.  Observed    Fitted
1881        155179  159065.7154
                    165281.5066
                    171412.0231
                    177443.1571
                    183361.9961
                    189156.8866
                    194817.4808
                    200334.7674
                    205701.0867
                    210910.132
1891        223314  215956.9368
                    220837.8509
                    225550.5055
                    230093.7686
                    234467.6931
                    238673.4581
                    242713.3047
                    246590.4685
                    250309.1086
                    253874.2355
1901        265780  257291.6383

Solution

  • Your data appear to increment by one year - if so, you could try something like:

    plot(x = seq(min(df$year, na.rm = TRUE), 
                   max(df$year, na.rm = TRUE)+9, by = 1),
           y = df$Fitted, pch = 25, bg = "seagreen", xlab = "Year")
    points(x = df$year, y = df$Observed, pch = 24, bg = "maroon")
    legend("topleft", c("Observed", "Fitted"), pch = 24:25, 
           pt.bg = c("maroon","seagreen"), bty = "n")
    

    enter image description here

    Data:

    df <- read.table(text = "year  Observed    Fitted
    1881        155179  159065.7154
    NA NA                    165281.5066
    NA NA                    171412.0231
    NA NA                    177443.1571
    NA NA                    183361.9961
    NA NA                    189156.8866
    NA NA                    194817.4808
    NA NA                    200334.7674
    NA NA                    205701.0867
    NA NA                    210910.132
    1891        223314  215956.9368
    NA NA                    220837.8509
    NA NA                    225550.5055
    NA NA                    230093.7686
    NA NA                    234467.6931
    NA NA                    238673.4581
    NA NA                    242713.3047
    NA NA                    246590.4685
    NA NA                    250309.1086
    NA NA                    253874.2355", h = TRUE)