How to unclutter the x-axis in a plot

Viewed 133

Using the R programming language, I create some time series data (daily measurements, over a period of 20 years). I aggregated this data at monthly time periods and then produced a graph:

library(ggplot2)

library(xts)

library(scales)

set.seed(123)

day = seq(as.Date("2000/1/1"), as.Date("2020/1/1"),by="day")

day <- format(as.Date(day), "%Y/%m/%d")

amount <- rnorm(7306 ,100,10)

data <- data.frame(day, amount)

y.mon<-aggregate(amount~format(as.Date(day),
format="%Y/%m"),data=data, FUN=sum)

y.mon$d = y.mon$`format(as.Date(day), format = "%Y/%m")`

ggplot(y.mon, aes(x = d, y=amount))+
         geom_line(aes(group=1))

enter image description here

  1. Right now, the x-axis is completely unreadable. Is there a way to "unclutter" the x-axis? Perhaps "slant" the dates or show the dates at intervals of 4 month periods? I can completely delete the x-axis but ideally I would like to keep it there for reference.

  2. At the end of the graph, there is a huge downwards "spike". I think this is because the data is aggregated every month - and since the last day the data is available at is "Jan-01-2020", this causes the "downwards spike". Is it possible to "query" the "y.mon" object so that the graph is made only until the last "complete" time period? This "spike" is deceiving, someone might look at the graph and think a big anomaly happened in Jan-2020, but it's actually because there is only 1 measurement at this time.

Thanks

1 Answers

You can also try:

library(ggplot2)
library(xts)
library(scales)
set.seed(123)
#Data
day = seq(as.Date("2000/1/1"), as.Date("2020/1/1"),by="day")
amount <- rnorm(7306 ,100,10)
data <- data.frame(day, amount)
#Aggregate
y.mon<-aggregate(amount~format(as.Date(day),
                               format="%Y/%m"),data=data, FUN=sum)
#Count days
y.mon2<-aggregate(amount~format(as.Date(day),
                               format="%Y/%m"),data=data,
                  FUN=function(x) length(x))
names(y.mon2)[2]<-'N'
#Format and merge to add N
y.mon$d = y.mon$`format(as.Date(day), format = "%Y/%m")`
mmon <- merge(y.mon,y.mon2)
#Add a dummy date
mmon$d <- as.Date(paste0(mmon$d,'/01'),'%Y/%m/%d')
#Plot
ggplot(subset(mmon,N!=1), aes(x = d, y=amount))+
  geom_line(aes(group=1))+
  scale_x_date(date_breaks = '4 month',date_labels = '%Y-%m',
               expand = c(0,0))+
  theme(axis.text.x = element_text(angle = 90))

Output:

enter image description here

Update: Using previous code and only changing for labels:

#Plot Update
ggplot(subset(mmon,N!=1), aes(x = d, y=amount))+
  geom_line(aes(group=1))+
  scale_x_date(date_breaks = '12 month',date_labels = '%Y',
               expand = c(0,0))+
  theme(axis.text.x = element_text(angle = 90))

Output:

enter image description here

Related