Raul
Raul

Reputation: 269

Plotting this weeks data versus last weeks in ggplot

I have a datasets structured the following way

date    transaction 
8/15/2020   585
8/14/2020   780
8/13/2020   1427.8
8/12/2020   4358
8/11/2020   780.9
8/8/2020    585
8/6/2020    1107.4
8/5/2020    2917.35
8/4/2020    1237.1

Is there a way to plot a line graph with all the transactions that occurred this week compared to the previous week? I tried filtering the data manually and assigning it to a new dataframe which seemed to work but its very manual intensive. Would it be possible to use today() and have it register the day of execution and run the results from there? Thanks!

Upvotes: 0

Views: 44

Answers (1)

r2evans
r2evans

Reputation: 160437

To do that, you need

  1. real Date (using as.Date), so that we can deal with them numerically (not categorically), and so that we can break them into weeks;
  2. use format to get each date's week-of-the-year; and
  3. facet_wrap so that we can use facets and have distinct x axes.
dat$date <- as.Date(dat$date, format = "%m/%d/%Y")
dat$week <- format(dat$date, format = "%V") # or %W

library(ggplot2)
ggplot(dat, aes(date, transaction)) +
  facet_wrap("week", ncol = 1, scales = "free_x") +
  geom_path()

ggplot2 with facets by-week

Upvotes: 1

Related Questions