代码之家  ›  专栏  ›  技术社区  ›  Geo-sp

ggplot2,填充线下区域时出错

  •  1
  • Geo-sp  · 技术社区  · 8 年前

    我有这个数据集,我想填写 area under each line 然而,我得到一个错误,说:

    错误:stat_bin()不能与y美学一起使用。

    此外,我需要使用 alpha 透明度的价值。有什么建议吗?

    library(reshape2)
    library(ggplot2)
    
    dat <- data.frame(
        a = rnorm(12, mean = 2, sd = 1),
        b = rnorm(12, mean = 4, sd = 2),
        month = c("JAN","FEB","MAR",'APR',"MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"))
    
    dat$month <- factor(dat$month, 
        levels = c("JAN","FEB","MAR",'APR',"MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"), 
        ordered = TRUE)
    
    dat <- melt(dat, id="month")
    
    ggplot(data = dat, aes(x = month, y = value, colour = variable)) + 
        geom_line() + 
        geom_area(stat ="bin")
    
    2 回复  |  直到 8 年前
        1
  •  10
  •   Gregor Thomas    8 年前

    我想填充每行下面的区域

    这意味着我们需要指定 fill 美学

    我得到一个错误,说 "Error: stat_bin() must not be used with a y aesthetic."

    这意味着我们需要删除您的 stat ="bin" 密码

    此外,我需要使用alpha值作为透明度。

    这意味着我们需要 alpha = <some value> geom_area

    还有两件事:(1)由于在x轴上有一个因子,我们需要指定一个分组 ggplot 知道要连接哪些点。在这种情况下,我们可以使用 variable geom_area 是堆叠区域而不是重叠区域。因为您询问透明度,我假设您希望它们重叠,所以我们需要指定 position = 'identity' .

    ggplot(data = dat, aes(x = month, y = value, colour = variable)) +
        geom_line() +
        geom_area(aes(fill = variable, group = variable),
                  alpha = 0.5, position = 'identity')
    

    enter image description here

        2
  •  2
  •   alistaire    8 年前

    要跨类别变量获取行,请使用 group 美学:

    ggplot(data = dat, aes(x = month, y = value, colour = variable, group = variable)) + 
        #geom_line(position = 'stack') +   # redundant, but this is where lines are drawn
        geom_area(alpha = 0.5)
    

    area plot

    要更改内部颜色,请使用 fill 美学