gpt4 book ai didi

r - 填充ggplot2 : geom_area()中折线图下的区域

转载 作者:行者123 更新时间:2023-12-03 22:23:13 28 4
gpt4 key购买 nike

对于数据:

    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() ] 下的区域着色为值(value)“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)

阴谋

enter image description here

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com