ggplot2,在

时间:2016-12-19 20:20:39

标签: r plot ggplot2

我有这个数据集,我想填写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 个答案:

答案 0 :(得分:4)

  

我想填写每行下面的区域

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

  

我收到错误"Error: stat_bin() must not be used with a y aesthetic."

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

  

此外,我需要使用alpha值来实现透明度。

这意味着我们需要将alpha = <some value>放入geom_area图层。

另外两件事:(1)因为你在x轴上有一个因子,我们需要指定一个分组,以便ggplot知道要连接的点。在这种情况下,我们可以使用variable作为石斑鱼。 (2)默认&#34;位置&#34; 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

答案 1 :(得分:2)

要获取分类变量之间的线条,请使用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美学。

相关问题