对于数据:

    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)

最佳答案

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


情节

关于r - 填写ggplot2中线图下方的区域:geom_area(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28730083/

10-11 10:23