我有一个数据框新,如下所示:
> new
group date relamount average
1 1 2012-07-01 2.3498695 1.524178
2 1 2012-08-01 0.6984866 1.524178
3 2 2012-09-01 0.9079118 1.896867
4 2 2012-10-01 2.8858218 1.896867
5 3 2012-11-01 1.2406948 1.777372
6 3 2012-12-01 2.3140496 1.777372
7 4 2013-01-01 1.5904573 2.421820
8 4 2013-02-01 3.2531825 2.421820
9 5 2013-03-01 4.2962963 3.812503
10 5 2013-04-01 3.3287101 3.812503
11 6 2013-05-01 3.7698413 2.603770
12 6 2013-06-01 1.4376997 2.603770
13 7 2013-07-01 5.0687285 4.760392
14 7 2013-08-01 4.4520548 4.760392
15 8 2013-09-01 5.5063913 5.537038
16 8 2013-10-01 5.5676856 5.537038
17 9 2013-11-01 6.2686567 8.644863
18 9 2013-12-01 11.0210697 8.644863
我绘制数据(在x轴上{date
,在y轴上relamount
),并将new$group
作为垂直线。
我想要的东西:
基于new$average
的垂直线之间的 水平线 ...到目前为止,尝试使用geom_segment
来做到这一点:
我知道我必须为geom_segment
有一个特定的起点和终点,但是也许我也可以这样做吗?不出所料,它没有用。
seq <- seq(2, nrow(df1), by=2) # points for vertical lines
ggplot(new, aes(date, relamount)) + # plot data
geom_line() +
geom_vline(xintercept = new$date[seq]) # create vertical lines
geom_segment(data = new, aes(x = new$group, # create horiz. lines
y = new$average,
xend = new$group +1,
yend = new$average))
所以我只想在垂直线之间使用红线(new$average
)。
答案 0 :(得分:3)
library(ggplot2)
new = read.table(text = "
group date relamount average
1 1 2012-07-01 2.3498695 1.524178
2 1 2012-08-01 0.6984866 1.524178
3 2 2012-09-01 0.9079118 1.896867
4 2 2012-10-01 2.8858218 1.896867
5 3 2012-11-01 1.2406948 1.777372
6 3 2012-12-01 2.3140496 1.777372
7 4 2013-01-01 1.5904573 2.421820
8 4 2013-02-01 3.2531825 2.421820
9 5 2013-03-01 4.2962963 3.812503
10 5 2013-04-01 3.3287101 3.812503
11 6 2013-05-01 3.7698413 2.603770
12 6 2013-06-01 1.4376997 2.603770
13 7 2013-07-01 5.0687285 4.760392
14 7 2013-08-01 4.4520548 4.760392
15 8 2013-09-01 5.5063913 5.537038
16 8 2013-10-01 5.5676856 5.537038
17 9 2013-11-01 6.2686567 8.644863
18 9 2013-12-01 11.0210697 8.644863
", header=T)
# get points for vertical lines
seq <- seq(2, nrow(new), by=2)
ggplot() +
geom_line(data=new, aes(date, relamount, group=1)) + # plot line of data points
geom_vline(xintercept = as.numeric(new$date[seq])) + # plot vertical lines
geom_segment(data=new[seq,], aes(x=as.numeric(date)-2, # plot horizontal lines (segments)
xend=as.numeric(date),
y=average,
yend=average), col="red") +
scale_x_discrete(breaks = new$date[seq], labels = new$date[seq]) # adjust x axis labels