0

I want to create a graph which has 36 ticks on the x-axis displaying text.

I have df for this example i'll want 12 ticks displaying text.

period  agg1  agg2
201601   1      2
201602   2      2 
201603   3      2 
  .      .      .
  .      .      .
  .      .      .
201612   4      1

period is numeric, in the form YYYYMM so I've changed it to a date

for (row in 1:nrow(df)){
  df[row,'period'] <- df[row,'period'] %>%
    mutate(period = as.Date(as.character(period*100+25),"%Y%m%d"))
}

melted the data

long_df <- melt(df, id = "period")

I plotted the data using:

df_plot <- ggplot(data = long_df,
                aes(x = period, y = value, colour = variable)) + 
                geom_line()

# adding titles & labels
df_plot + labs(title = "Aggregates", colour = "Method") + 
              xlab("Period") + 
              ylab("Agg, £million") +
  scale_x_discrete(breaks = c("201601", "201602", "201603", "201604", "201605", "201606", "201607", "201608", "201609", "201610", "201611", "201612"))

This creates a graph where the ticks are in the correct place, but the text doesn't show at the tick.

I tried adding the labels = c() argument but it doesn't show anything

df_plot + labs(title = "Aggregates", colour = "Method") + 
              xlab("Period") + 
              ylab("Agg") +
  scale_x_discrete(breaks = c("201601", "201602", "201603", "201604", "201605", "201606", "201607", "201608", "201609", "201610", "201611", "201612"), 
                   labels = c("201601", "201602", "201603", "201604", "201605", "201606", "201607", "201608", "201609", "201610", "201611", "201612"))

I found this: ggplot x-axis labels with all x-axis values but according to the solution my labels argument should work?

Laura
  • 177
  • 1
  • 12
  • 3
    If your x-axis is a date, you want to use something like `scale_x_date(date_breaks = "1 day", date_labels = "%Y%m")`. See this question/answer: https://stackoverflow.com/questions/60764841/problems-with-scale-x-continuous/60765148#comment107510236_60765148 – Dave2e Mar 27 '20 at 15:25
  • 1
    @Laura: you don't have to use a `for` loop to change the date. Just use `mutate` directly on `df`. It will work for all the rows – Tung Mar 27 '20 at 15:30

1 Answers1

0
# formatting period to date
library(zoo) # additional library required

df$period <- sapply(df$period,as.character)
#sapply(df$period, class)

for (row in 1:nrow(df)){
 df$period <- zoo::as.Date(zoo::as.yearmon(df$period, "%Y%m"))


# plot
df_plot <- ggplot(data = long_df,
                aes(x = period, y = value, colour = variable)) + 
                geom_line()
df_plot + labs(title = "Aggregates", colour = "Method") + 
              xlab("Period") + 
              ylab("Agg, £million") +
              scale_x_date(breaks = "1 month", date_labels = "%Y%m") +
              theme(axis.text.x = element_text(angle = 90, hjust = 1)) # to rotate 90 degrees 

Laura
  • 177
  • 1
  • 12