繁体   English   中英

GGplot 的问题:将衰退条附加到 R 中的条形图

[英]Problem with GGplot: attaching recession bars to a bar chart in R

我一直在尝试为英国的 GDP 增长建立一个条形图,并用衰退带覆盖它。 我可以用 plot 条做必要的事情,但是当我用衰退带覆盖时,我得到一个错误,说找不到变量。

uk.recessions.df <- read.table(textConnection(
"Peak, Trough
1857-06-01, 1858-12-01
1867-06-01, 1869-12-01
1873-10-01, 1879-03-01
1882-03-01, 1885-05-01
1887-03-01, 1888-04-01
1890-07-01, 1891-05-01
1893-01-01, 1894-06-01
1895-12-01, 1897-06-01
1919-03-01, 1921-07-01
1930-01-01, 1931-12-01
1956-04-01, 1956-08-01
1961-07-01, 1962-01-01
1973-09-01, 1974-04-01
1975-04-01, 1975-10-01
1980-01-01, 1981-04-01
1990-07-01, 1991-09-01
2008-04-01, 2009-07-01
2020-01-01, 2020-07-01"), sep=',',
colClasses=c('Date', 'Date'), header=TRUE)

uk.recessions.trim.df <- subset(uk.recessions.df, Peak >= min(tbl.QQGDP$Date))

tbl.data <- tbl.QQGDP %>%
  mutate(Value = GDPGrowth < 0) 

p <- ggplot(data = tbl.data, aes(x = Date, y = GDPGrowth, fill = Value)) + 
  geom_col(position = "identity", colour = "black", size = 0.25) + 
  scale_fill_manual(values = c("#85225f","#dbab01"), guide = FALSE) +
  theme_tq() 


p <- p + 
  geom_rect(data = uk.recessions.trim.df,
            aes(xmin = Peak, xmax = Trough, ymin = -Inf, ymax = Inf),
            fill = "grey", alpha = 0.5)

p

我得到的错误是Error in FUN(X[[i]], ...): object 'GDPGrowth' not found

我无法弄清楚我做错了什么。 任何帮助(即使是因为一个愚蠢的错误而告诉我。!)将不胜感激。

默认情况下, geom_*()元素从 plot ( ggplot() ) 的顶层继承美学映射。 在您的情况下, geom_rect()调用继承了aes(x = Date, y = GDPGrowth, fill = Value)但找不到这些对象,因为您有不同的数据源( uk.recessions.trim.df而不是tbl.data . tbl.data )。

如果您将选项inherit.aes = FALSE添加到geom_rect() ,您将获得所需的 plot。

p <- ggplot(data = tbl.data, aes(x = Date, y = GDPGrowth, fill = Value)) +
     geom_col(position = "identity", colour = "black", size = 0.25) +
     scale_fill_manual(values = c("#85225f","#dbab01"), guide = FALSE)


p <- p +
     geom_rect(data = uk.recessions.trim.df,
               aes(xmin = Peak, xmax = Trough, ymin = -Inf, ymax = Inf),
               fill = "grey", alpha = 0.5,
               inherit.aes = FALSE)

p

另一种方法(可能是更好的方法)是在每个 geom 中分别定义数据和 aes,而不是在初始ggplot()调用中。 例如:

p <- ggplot() + 
     geom_col(data = tbl.data, 
              aes(x = Date, y = GDPGrowth, fill = Value),
              position = "identity", colour = "black", size = 0.25) + 
     scale_fill_manual(values = c("#85225f","#dbab01"), guide = FALSE) 


p <- p + 
     geom_rect(data = uk.recessions.trim.df,
               aes(xmin = Peak, xmax = Trough, ymin = -Inf, ymax = Inf),
               fill = "grey", alpha = 0.5)

p

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM