0

I am ultimately trying to create a PDF that contains several plots using a for loop. When I run the plots individually I get a warning message, but the plot generates. However, when I run the plots in a for loop, the plots do not generate. I think this is because the for loop stops after the first warning message appears.

Here is the code for a singular plot which has a warning message but generates a plot:

ggplot(raw[raw$Sector==sectorname,],aes(x=SEP_Score)) + 
  geom_histogram() + 
  facet_grid(~LabelYear_AUTO) + 
  stat_bin(breaks=rng) + 
  scale_y_continuous(name = "Count")

When I run this code, a plot generates but I receive the following warning:

`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Again, I'm fine with the binwidth. I don't want to change anything.

Now when I modify the code slightly so that multiple plots would generate no plots show in my viewer. Here is the code I've used.

for (i in 1:nrow(table(raw$Sector))){

 sectorname=rownames(table(raw$Sector))[i]

 ggplot(raw[raw$Sector==sectorname,],aes(x=SEP_Score)) + 
   geom_histogram() + 
   facet_grid(~LabelYear_AUTO) + 
   stat_bin(breaks=rng) + 
   scale_y_continuous(name = "Count"))
}

How do I tell R to ignore all warning messages and just run the task I want it to?

I've tried the following code by wrapping try around the problematic text to no avail.

for (i in 1:nrow(table(raw$Sector))){

 sectorname=rownames(table(raw$Sector))[i]
  try(ggplot(raw[raw$Sector==sectorname,],aes(x=SEP_Score)) + 
        geom_histogram() +
        facet_grid(~LabelYear_AUTO) +   
        stat_bin(breaks=rng) + 
        scale_y_continuous(name = "Count")
      )
    }
Daniel Anderson
  • 2,394
  • 13
  • 26
Danny
  • 554
  • 1
  • 6
  • 17
  • What you're receiving is not a warning, but a message. Try explicitly adding a `print()` statement around your ggplot code. – Daniel Anderson Jan 30 '18 at 18:51
  • `?suppressMessages()` – David Klotz Jan 30 '18 at 18:52
  • Both print() and suppressMessages() generate the same message/warning – Danny Jan 30 '18 at 18:54
  • 1
    If you just want to suppress the message, but keep the bins the same, just do `geom_histogram(bins = 30)`. – Daniel Anderson Jan 30 '18 at 18:59
  • Adding geom_histogram(bins = 30) suppressed the message. However, multiple plots are still not generating. – Danny Jan 30 '18 at 19:16
  • Possible duplicate of [R: ggplot does not work if it is inside a for loop although it works outside of it](https://stackoverflow.com/questions/15678261/r-ggplot-does-not-work-if-it-is-inside-a-for-loop-although-it-works-outside-of) – ngm Jan 30 '18 at 19:55
  • It works for me when the plot is wrapped in print(). Do you have any sample data? – Martin Boros Jan 30 '18 at 20:12

0 Answers0