ggplot中分类轴限制的问题

时间:2017-01-05 19:16:42

标签: r ggplot2

我的分类x轴限制有问题。这是我的数据框sub1

structure(list(YR = structure(1:83, .Label = c("1886", "1888", 
"1890", "1899", "1903", "1923", "1930", "1935", "1936", "1938", 
"1939", "1940", "1942", "1943", "1946", "1947", "1948", "1949", 
"1950", "1952", "1953", "1954", "1955", "1956", "1957", "1959", 
"1960", "1961", "1962", "1963", "1964", "1965", "1966", "1967", 
"1968", "1969", "1970", "1971", "1972", "1973", "1974", "1975", 
"1976", "1977", "1978", "1979", "1980", "1981", "1982", "1983", 
"1984", "1985", "1986", "1987", "1988", "1989", "1990", "1991", 
"1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999", 
"2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", 
"2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", 
"2016"), class = "factor"), Freq = c(0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 
0L, 1L, 1L, 0L, 4L, 2L, 0L, 1L, 2L, 0L, 0L, 1L, 4L)), .Names = c("YR", 
"Freq"), row.names = 84:166, class = "data.frame")

这是剧情剧本:

ggplot(sub1, aes(x=YR,y=Freq)) + 
  scale_y_continuous(limit=c(0,8),expand=c(0, 0)) +
  scale_x_discrete(breaks=c("1965","1970","1975","1980",
                            "1985","1990","1995","2000",
                            "2005","2010","2015")) +
  geom_bar(stat="identity") + 
  xlab("") + ylab("No of papers")

以下是情节:

enter image description here

然后,当我再添加几个x轴断点时:

ggplot(sub1, aes(x=YR,y=Freq)) + 
  scale_y_continuous(limit=c(0,8),expand=c(0, 0)) +
  scale_x_discrete(breaks=c("1920","1925","1930","1935","1940","1945",
                            "1950","1955","1960","1965","1970","1975",
                            "1980","1985","1990","1995","2000",
                            "2005","2010","2015")) +
  geom_bar(stat="identity") + 
  xlab("") + ylab("No of papers")

x轴发生了一些特殊的事情:

enter image description here

哪里有错误?

1 个答案:

答案 0 :(得分:1)

您的YR因素缺失了数年。 R不知道这些年份,只是一系列因素。

在运行ggplot之前包含此代码:

sub1 <- merge(data.frame(YR=1886:2016), sub1, all.x = TRUE)
sub1$YR <- as.factor(sub1$YR)
sub1[is.na(sub1)] <- 0