【问题标题】:Label every year on x-axis even if some years have no observations in R即使有些年份在 R 中没有观察到,也要在 x 轴上标注每年
【发布时间】:2026-02-02 06:35:01
【问题描述】:

我正在尝试在 R 中制作一个条形图,x 轴为 1975-2015 年。年份在变量data3$q18yearFirstSclLens 中。

我知道岁月:

> 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 

然后绘制我的条形图:

> bp <- barplot(yearcount2, main="", xlab="", ylab="", ylim=c(0,100), las=2, cex.names=0.75, xaxt="n")

但当然,我只得到有观察的年份。如何绘制从 1975 年到 2015 年的所有年份的 x 轴图,包括没有观察的年份?

这里是dput 信息:

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

感谢您的帮助!

【问题讨论】:

    标签: r plot bar-chart axis axis-labels


    【解决方案1】:

    你可以这样做

    minyr <- min(names(yearcount2)); maxyr <- max(names(yearcount2))
    barplot(setNames(yearcount2[as.character(minyr:maxyr)], minyr:maxyr), las=2)
    

    【讨论】:

    • 效果很好,我从没想过。谢谢!