如何使用ggplot填充geom_area()图形?

6
我有一个类似这样的geom_area图:area plot 我想将x轴上方的所有内容变成绿色,将x轴下面的所有内容变成红色。我的数据中有一个类别列,其中包含所有正值的字符串“positive”和所有负值的字符串“negative”,所以我尝试使用fill = category,并使用scale_fill_manual将正值设置为绿色,将负值设置为红色,但是结果如下图所示: colored area plot 绿色在x轴上方看起来正确,但是在x轴下方的红色不正确。我检查了我的数据,在Oct20之后没有负数据点,使用geom_point时得到了正确的颜色。
以下是我的一些数据样本:
created                 score   category
2011-10-19 21:26:19     2   positive
2011-10-19 22:50:33    -2   negative
2011-10-20 15:12:38    -2   negative
2011-10-20 17:19:24    -2   negative
2011-10-20 22:12:44     2   positive
2011-10-20 22:16:57     4   positive
2011-10-21 08:22:53     2   positive

以下是我用来绘制图表的代码:

ggplot(data = df, aes(x = created, y = score, colour = category)) + geom_point(aes(fill = category)) + scale_fill_manual(values = c("positive" = "green", "negative" = "red"))

我的问题可能与这个之前的问题相关。


注:本文中的“plot”指“图表”。

2
这篇博客文章可能会有所帮助:http://learnr.wordpress.com/2009/10/22/ggplot2-two-color-xy-area-combo-chart/#more-2195 - joran
1个回答

8

您需要为每个正/负段创建一个新的分组变量。为了使过渡更加自然,您可以先插值数据:

require(ggplot2)

# Load data
df = read.table('data.txt', header=T)
df$created = as.POSIXct(df$created, tz='UTC')

# Interpolate data
lin_interp = function(x, y, length.out=100) {
    approx(x, y, xout=seq(min(x), max(x), length.out=length.out))$y
}
created.interp = lin_interp(df$created, df$created)
created.interp = as.POSIXct(created.interp, origin='1970-01-01', tz='UTC')
score.interp   = lin_interp(df$created, df$score)
df.interp = data.frame(created=created.interp, score=score.interp)

# Make a grouping variable for each pos/neg segment
cat.rle = rle(df.interp$score < 0)
df.interp$group = rep.int(1:length(cat.rle$lengths), times=cat.rle$lengths)

# Plot
dev.new(width=6, height=4)
ggplot(data = df.interp, aes(x = created, y = score, fill=score>0, group=group)) + geom_area() + scale_fill_manual(values = c('green', 'red'))

enter image description here


顺便提一下,我从你的示例数据中引用了created列以便更容易地加载。 - John Colby
@WilliamGunn 太好了,我很高兴它起作用了。我自己也刚学习了rle :) - John Colby
这个解决方案是一个近似值,当数值反复穿过轴时效果不佳。(请注意红绿转换处的小间隙。)请参见此问题以比较三种解决该问题的方法。 - beroe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接