Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a proper title to ggplot

Tags:

r

ggplot2

I've been trying this all morning and still can't find a solution after reading related post on stackoverflow

I have the following code:

names <- colnames(df[17:length(df)])

counter = 17L

for (i in 1:length(names)) {
  df.tax <- subset(df, df[,c(counter)] != 0)
  counter = counter + 1L
  meta <- subset(df.tax, select=c(1:16))
  meltmeta <- melt(meta, id=c("Collector", "Year","Week","Cities","Provinces"))
  ppv <- ggplot(meltmeta, aes(title = paste(names[i]), factor(Provinces), value))
  ppv + geom_boxplot() + geom_boxplot(aes(fill=Collector), alpha=I(0.5)) + geom_point(aes(color=Collector), size=1) +facet_wrap(~variable, scale="free")
  ggsave(file = paste(names[i], sep=".","provinces_vs_climate.pdf"), width=16, height=8)
}

My issue is, I can't add a proper title for ggplot. At every iteration of the for loop, I am generating a new dataframe called df.tax by subsetting parts of df. I melt df and then trying to generate a plot using ggplot.

I managed to save each plot with a different file name (based on the names array) every iteration on ggsave, but ggplot just keep on generating the title "paste(names[i])" for each plot.

I tried, get(), paste(), labs()...etc, but none work

Anyone know how I can resolve this issue?

like image 999
WonderSteve Avatar asked Apr 08 '13 20:04

WonderSteve


1 Answers

As mentioned by joran, since version 0.9.2 of ggplot2, the easiest way to set a title for your plot is to use ggtitle. Using ggtitle your code would look something like this:

for (i in 1:length(names)) {
  df.tax <- subset(df, df[,c(counter)] != 0)
  counter = counter + 1L
  meta <- subset(df.tax, select=c(1:16))
  meltmeta <- melt(meta, id=c("Collector", "Year","Week","Cities","Provinces"))
  ppv <- ggplot(meltmeta, aes(factor(Provinces), value))
  ppv <- ppv + geom_boxplot() 
  ppv <- ppv + geom_boxplot(aes(fill=Collector), alpha=I(0.5)) 
  ppv <- ppv + geom_point(aes(color=Collector), size=1) 
  ppv <- ppv + facet_wrap(~variable, scale="free")
  ppv <- ppv + ggtitle(paste(names[i]))
  ggsave(file = paste(names[i], sep=".","provinces_vs_climate.pdf"), width=16, height=8)
}
like image 131
Wilduck Avatar answered Sep 27 '22 01:09

Wilduck