Reputation: 169
I have a dataframe new which looks like this:
> 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
I plot the data (date
on x axis, relamount
on y axis) and have new$group
as vertical lines.
What I want:
Horizontal lines between the vertical lines based on new$average
...so far tried to do it like this with geom_segment
:
I know I have to have a specific start and end point for geom_segment
, but maybe I can also do it like this? As expected it didn't work.
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))
So I just want to have the red lines (new$average
) between the vertical lines.
Upvotes: 1
Views: 1078
Reputation: 16121
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
Upvotes: 4