簡體   English   中英

ggplot中分類軸限制的問題

[英]Problems with limits of categorical axis in ggplot

我在分類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")

這是情節:

在此處輸入圖片說明

然后,當我添加更多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軸發生一些奇怪的事情:

在此處輸入圖片說明

錯誤在哪里?

您的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM