简体   繁体   English

如何使用geom_rect在ggplot中填充geom_line图下方的区域?

[英]How to fill area bellow geom_line plot in ggplot with geom_rect?

This is my plot:这是我的情节:

library(ggplot2)
economics <- economics %>% mutate(year = year(economics$date))

ggplot(economics,aes(year, unemploy))+
  geom_line() +
  geom_rect(aes(xmin = 1970,xmax = 1975,
                     ymin = 0, ymax = unemploy))

I want to fill the area bellow the line plot between the years 1970 and 1975. But its not working.我想填充 1970 年和 1975 年之间的线图下方的区域。但它不起作用。

What am I doing wrong?我究竟做错了什么?

You can choose a ymax that makes sense to you.您可以选择对您有意义的ymax For example, I set ymax = 4800 :例如,我设置ymax = 4800

library(ggplot2)
ggplot(economics,aes(year, unemploy))+
        geom_rect(aes(xmin = 1970,xmax = 1975,
                      ymin = 0, ymax = 4800), fill = "lightblue", alpha = .5) +
        geom_line()

在此处输入图片说明

The issue is that in ymax we are using the whole column 'unemploy', it should be the max value of 'unemploy' within that range of year问题是在ymax我们使用的是整列“失业”,它应该是该年份范围内“失业”的max

library(ggplot2)
library(dplyr)
library(lubridate)
economics %>%
    mutate(year = year(date)) %>% 
    ggplot(aes(year, unemploy)) + 
        geom_line() +
   geom_rect(aes(xmin = 1970,xmax = 1975,
                      ymin = 0,
        ymax = max(.data[['unemploy']][between(.data[['year']], 1970, 1975)]))) + 
    theme_bw()

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

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