在ggplot2中填充线图下的区域:geom_area() [英] Filling in the area under a line graph in ggplot2: geom_area()
问题描述
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
$ / code>
如果我向点添加一行,如何使用ggplot2以不同的颜色为行号[geom_area()]对价值neg和pos进行着色?
pre $ g $ p $ ggplot(aes(x = period ,y = def.percent,group = 1))+
geom_area(aes(fill = valence))+
geom_line()+ geom_point()+ geom_hline(yintercept = 0)
但是R返回错误:
错误:美学不能随着功能区而变化
这个代码适用于不同的数据集,我不明白这里发生了什么,例如:
library(gcookbook)#对于数据集
cb < - 子集(气候,酸味ce ==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
是一个分类,即因子
变量。如果您将它转换为数字
,它可以正常工作:
数据
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)
Plot
p>
For the data:
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
If I add a line to the points, how can I use ggplot2 to color the area under the line [ geom_area() ] with different colors for the valence values "neg" and "pos"?
I tried this:
ggplot(data, aes(x=period, y=def.percent, group = 1)) +
geom_area(aes(fill=valence)) +
geom_line() + geom_point() + geom_hline(yintercept=0)
But R returns the error:
Error: Aesthetics can not vary with a ribbon
This same code works for a different dataset, I don't understand what is happening here, for example:
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)
This happens because in your case period
is a categorical i.e. a factor
variable. If you convert it to numeric
it works fine:
Data
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')
Solution
ggplot(df, aes(x=period, y=def.percent)) +
geom_area(aes(fill=valence)) +
geom_line() + geom_point() + geom_hline(yintercept=0)
Plot
这篇关于在ggplot2中填充线图下的区域:geom_area()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!