更改折线图特征以通知这些值是预测值

时间:2013-11-18 15:28:19

标签: r ggplot2

假设我有以下数据,并希望使用ggplot2绘制折线图。数据包括五天的数据,星期四和星期五是预测。我怎样才能创建一些方案来从星期四到星期五(或不同的颜色背景)划线,以便我有一种直观的方式来表示这些值是预测。

示例数据:

df = data.frame(date=c("mon","tues","wed","thurs","fri"),
                gals=c(4,6,2,5,3),
                cups=c(30,25,27,22,25))
df
library(reshape)
d = melt(df, id="date")
d
ggplot(d, aes(date, value, group=variable, colour=variable)) + geom_line(lwd=1.15) 

1 个答案:

答案 0 :(得分:1)

你必须像这样绘制2条线,并为每条线分组数据。请记住向“已知”系列添加一个点,以便它与“未知”数据结合:

require(reshape)
df = data.frame(date=c("mon","tues","wed","thurs","fri"),
            gals=c(4,6,2,5,3),
            cups=c(30,25,27,22,25))

d = melt(df, id="date")
# select the points you know + 1 to join up the line
known<-d[which(d$date %in% c("mon","tues","wed","thurs")),]
# select the points you don't know
unknown<-d[which(d$date %in% c("thurs","fri")),]

ggplot() + 
   geom_line(data=known, aes(x=date, y=value, group=variable, colour=variable)) + 
# use linetype=2 for a dotted line
geom_line(data=unknown, aes(x=date, y=value, group=variable, colour=variable), linetype=2) + 
 # this is to make the days display in order
scale_x_discrete(limits=c("mon","tues","wed","thurs","fri")) 

plot