6

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?

0

1 Answer 1

11

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)
}
Sign up to request clarification or add additional context in comments.

4 Comments

No need to link to my profile, or even mention me really. If I restrict myself to a comment it's because I don't have time/inclination to write an answer, and fully expect others to do so. :)
I'll remove the link if you'd prefer. Although I'm glad I clicked through it, personally, as I'm a fellow nordic skier/data analyst (what a pleasant surprise).
No need to remove it...just letting you know it's totally fine to poach any of my comments as answers, that's all.
Thank you very much! I didn't know about ggtitle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.