I have an excel graph that I want to create in R.
I tried recreating it with some dummy data
a<-rnorm(12)
a_ts<-ts(a, start=c(2015, 1), frequency=12)
a_time<-time(a_ts)
a_series<-ts.union(ret=a_ts, date=a_time)
a_series_df<-as.data.frame(a_series)
ggplot() +
geom_rect(data=data.frame(xmin=decimal_date(as.Date(c("2015-01-01"))),
xmax=decimal_date(as.Date(c("2015-05-31"))), ymin=-Inf, ymax=Inf),
aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax), fill="pink", alpha=0.5) +
geom_line(data = a_series_df, aes(x=date,y=ret, color='blue')) +
theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))
#this does not work
#scale_x_date(breaks = "1 month", minor_breaks = "1 month", labels=date_format("%B-%d")) +
#scale_y_continuous(labels = scales::percent)
which looks like this
I am struggling with the date conversions and also setting the x and y origins to zero and getting the axis labels right, the last two lines of code work for non-date data points. I would also like to have a legend below the chart for series1, series2 and and entry for the shaded area.
Any help would be appreciated.
Update after applying the suggestions:
Below is an example that should get you most of the way there. This uses the
lubridate
package for working with date and times (Dates in this case). This shows you one way you could plot two separate lines on the same plot with most of the requested modifications. In this example analpha
of0.05
is used.EDIT
Note, the
date_breaks
value can be changed to1 month
if you want to plot by month. This example is just per day.Just make sure the values are actual
Date
objects: