Search code examples
rggplot2formattingleftalign

Left align subheading in chart using ggplot


Anyone know how to left align the subheading in this chart I made? Not married to any of the methods I used, except using ggplot.

library(ggplot2)
library(ggthemes)
library(grid)

# Random exponential sample
set.seed(10)
n=20
y<-rexp(n=n)
y<-y[order(y)]
x<-seq(n)+1990
mydata<-data.frame(cbind(x,y))

# Plot
p <- (ggplot(mydata, aes(x=x, y=y))
  + geom_point(size=3,alpha=.50)
  + geom_smooth(method="lm",formula=y~poly(x,2,raw=T),se=F,size=1)
  + theme_economist(base_size=12, base_family="Avenir")
  + labs(title=expression(atop(bold("Inequality Is Increasing"), atop("Gini Coefficient", ""))))
  + labs(x="")
  + labs(y="")
  + annotate("text", label = "Source:World Bank Data", x = 2009, y = Inf, vjust = 61, size=4)
)

# Overide clipping
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)

Thanks


Solution

  • I experimented your codes quite a bit. Your original code works well when you want to have a subtitle. But what you sacrifice is left alignment. If you want left alignment, you can do something like ggtitle("Inequality Is Increasing\nGini Coefficient"). But, you sacrifice font stye, for example. This is a trade off. The only solution I can think is that you separate a subtitle from a main title. I rather treated the subtle as a text. I, therefore, used annotate. I played with x and y values to identify the best spot for your subtitle. This was purely experimental and tedious. But, I think this is the best I can offer for you. I hope this fulfils your requirements.

    # Plot
    p <- (ggplot(mydata, aes(x=x, y=y))
      + geom_point(size=3,alpha=.50)
      + geom_smooth(method="lm",formula=y~poly(x,2,raw=T),se=F,size=1)
      + theme_economist(base_size=12, base_family="Avenir")
      + ggtitle("Inequality Is Increasing")
      + annotate("text", x = 1992.25, y = 3.2, label = "Gini Coefficient", fontface = 3)
      + labs(x="")
      + labs(y="")
      + annotate("text", label = "Source:World Bank Data", x = 2009, y = Inf, vjust = 61, size=4)
    )