user2634146
user2634146

Reputation: 27

ggplot customize discrete axis label

I am trying to figure out a way to automate x-axis labels, when x is not continuous.

There are two things I am trying to do: (1) automatically create a vertical line at the end of each year (after every four quarters); (2) center x-axis labels indicating the year between two vertical lines (I am using spaces to do that). The last two lines of the code below do what I am trying to do.

    require(ggplot2)

    Quarter <- c("2010q1", "2010q2", "2010q3", "2010q4", "2011q1", "2011q2", "2011q3", "2011q4",
         "2012q1", "2012q2", "2012q3", "2012q4", "2013q1", "2013q2", "2013q3", "2013q4")
    rate <- c(1.6, 3.9, 2.8, 2.8, -1.3, 3.2, 1.4, 4.9,
            3.7, 1.2, 2.8, 0.1, 1.1, 2.5, 4.1,2.6)
    data  <- data.frame(Quarter, rate)

    ggplot(data, aes(x = Quarter, y = rate)) +
      geom_bar(stat="identity", fill = "darkorange1") +
      ylim(-10, 10) + 
      theme(axis.ticks.x = element_blank(),
      axis.title = element_blank(),
      axis.text.x = element_text(face = "bold"),
      panel.background = element_rect(fill = "transparent", color = NA),
      plot.background = element_rect(fill = "transparent", color = NA)) + 
     ## THIS IS WHERE I NEED HELP -
      geom_vline(xintercept = c(4.5, 8.5, 12.5, 16.5), linetype = 1, 
                 size = 0.1, color = "grey20") +
      scale_x_discrete(breaks=c("2010q2", "2011q2", "2012q2", "2013q2"),
                      labels = c("    2010", "    2011", "    2012", "    2013"))

I would appreciate any suggestions on how to do it more efficiently.

Upvotes: 0

Views: 1740

Answers (1)

MrFlick
MrFlick

Reputation: 206197

What if you split up the data in your "Quarter" column into "Year" and "YearQuarter" to have two levels of grouping. Then this strategy should work

require(ggplot2)
Year <- as.factor(rep(2010:2013, each=4))
YearQuarter <- rep(paste0("q",1:4), 4)
rate <- c(1.6, 3.9, 2.8, 2.8, -1.3, 3.2, 1.4, 4.9,
        3.7, 1.2, 2.8, 0.1, 1.1, 2.5, 4.1,2.6)
data  <- data.frame(rate, Year, YearQuarter)

And then plot it with

ggplot(data, aes(x = Year, y = rate)) +
    geom_bar(stat="identity",  aes(group=YearQuarter), 
       fill = "darkorange1", width=.75, position=position_dodge(width=1)) +
    ylim(-10, 10) + 
    theme(
        axis.ticks.x = element_blank(),
        axis.title = element_blank(),
        axis.text.x = element_text(face = "bold"),
        panel.background = element_rect(fill = "transparent", color = NA),
        plot.background = element_rect(fill = "transparent", color = NA)) + 
    geom_vline(xintercept = 1:3+.5, linetype = 1, 
        size = 0.1, color = "grey20")

And that makes this plot

enter image description here

Upvotes: 2

Related Questions