Reputation: 463
I am trying to make a barplot in R with the x-axis being years from 1975-2015. The years are in a variable data3$q18yearFirstSclLens
.
I get the years:
> yearcount2 <- table(data3$q18yearFirstSclLens)
> yearcount2
1976 1982 1983 1984 1985 1986 1987 1989 1991 1992 1993 1994 1995 1997 1998 1999 2000 2001 2002 2003
1 2 2 2 2 1 2 2 1 1 1 2 2 2 5 7 10 6 3 9
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
8 25 18 26 43 52 78 84 88 91 47 1
then plot my barplot:
> bp <- barplot(yearcount2, main="", xlab="", ylab="", ylim=c(0,100), las=2, cex.names=0.75, xaxt="n")
But of course I only get years for which there are observations. How can I make the x-axis plot all years from 1975-2015, including the years that have no observations?
Here is the dput
info:
> dput(yearcount2)
structure(c(1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L,
2L, 5L, 7L, 10L, 6L, 3L, 9L, 8L, 25L, 18L, 26L, 43L, 52L, 78L,
84L, 88L, 91L, 47L, 1L), .Dim = 32L, .Dimnames = structure(list(
c("1976", "1982", "1983", "1984", "1985", "1986", "1987",
"1989", "1991", "1992", "1993", "1994", "1995", "1997", "1998",
"1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006",
"2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014",
"2015")), .Names = ""), class = "table")
Thank you for your help!
Upvotes: 2
Views: 121
Reputation: 54237
You could do something like
minyr <- min(names(yearcount2)); maxyr <- max(names(yearcount2))
barplot(setNames(yearcount2[as.character(minyr:maxyr)], minyr:maxyr), las=2)
Upvotes: 3