填写ggplot2中的折线图下的区域:geom_area()

TWe*_*est 13 r ggplot2 aesthetics

对于数据:

    def.percent period  valence
1   6.4827843   1984-1985   neg
2   5.8232425   1985-1986   neg
3   -2.4003260  1986-1987   pos
4   -3.5994399  1987-1988   pos
Run Code Online (Sandbox Code Playgroud)

如果我在点上添加一条线,我怎样才能使用ggplot2为线条[geom_area()]下的区域着色,使用不同的颜色为"neg"和"pos"?

我试过这个:

ggplot(data, aes(x=period, y=def.percent, group = 1)) +
geom_area(aes(fill=valence)) +
geom_line() + geom_point() + geom_hline(yintercept=0)
Run Code Online (Sandbox Code Playgroud)

但是R返回错误:

Error: Aesthetics can not vary with a ribbon
Run Code Online (Sandbox Code Playgroud)

这个相同的代码适用于不同的数据集,我不明白这里发生了什么,例如:

library(gcookbook) # For the data set
cb <- subset(climate, Source=="Berkeley")
cb$valence[cb$Anomaly10y >= 0] <- "pos"
cb$valence[cb$Anomaly10y < 0] <- "neg"

ggplot(cb, aes(x=Year, y=Anomaly10y)) +
  geom_area(aes(fill=valence)) +
  geom_line() +
  geom_hline(yintercept=0)
Run Code Online (Sandbox Code Playgroud)

Lyz*_*deR 15

发生这种情况是因为在您的情况下period是分类即factor变量.如果你将它转换为numeric它工作正常:

数据

df <- read.table(header=T, text='  def.percent period  valence
1   6.4827843   1984   neg
2   5.8232425   1985   neg
3   -2.4003260  1986   pos
4   -3.5994399  1987   pos')
Run Code Online (Sandbox Code Playgroud)

ggplot(df, aes(x=period, y=def.percent)) +
  geom_area(aes(fill=valence)) +
  geom_line() + geom_point() + geom_hline(yintercept=0)
Run Code Online (Sandbox Code Playgroud)

情节

在此输入图像描述

  • 请注意,问题中的工作代码也具有这些未着色的区域。 (2认同)