【问题标题】:Filling in the area under a line graph in ggplot2: geom_area()在ggplot2中填充折线图下的区域:geom_area()
【发布时间】:2015-02-25 21:35:15
【问题描述】:

对于数据:

    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

如果我在点上添加一条线,我如何使用 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)

但是 R 返回错误:

Error: Aesthetics can not vary with a ribbon

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

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)

【问题讨论】:

    标签: r ggplot2 aesthetics


    【解决方案1】:

    发生这种情况是因为在您的情况下 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')
    

    解决方案

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

    剧情

    【讨论】:

    • 请注意,问题中的工作代码也有这些未着色的区域。
    • 是的,如果我们能隐藏无色区域就好了。