Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 plot title based on an iterating for loop variable

Tags:

r

ggplot2

I would like to title each plot with the variable (k) I am using to iterate within a for loop:

> MyData
     Name Stat Year value
1  Site01  Max 2013 29.88
2  Site01  Med 2013 29.67
3  Site01  Min 2013 29.16
4  Site01  Max 2020 31.21
5  Site01  Med 2020 30.38
6  Site01  Min 2020 29.38
7  Site01  Max 2040 35.50
8  Site01  Med 2040 33.17
9  Site01  Min 2040 29.60
10 Site02  Max 2013 53.70
11 Site02  Med 2013 53.49
12 Site02  Min 2013 53.20
13 Site02  Max 2020 53.10
14 Site02  Med 2020 53.01
15 Site02  Min 2020 52.55
16 Site02  Max 2040 52.04
17 Site02  Med 2040 51.74
18 Site02  Min 2040 50.98

pdf("plots.pdf")
for (k in unique(MyData$Name)){
subdata <- subset(MyData, Name == k)

     print(ggplot(subdata, aes(x = Year, y = value, colour = Stat)) 
          + geom_line() + expand_limits(y=c(0,100)) + ggtitle(k))

}
dev.off()

The plots are generated just fine when using a string for ggtitle() (for example: ggtitle("Name")) or after removing ggtitle() completely.

Any suggestions for how to include the value of the iterator variable (k) as the title on each plot?

like image 515
viridius Avatar asked Oct 20 '25 15:10

viridius


2 Answers

What class are the data in MyData$Name ?

Try replacing ggtitle(k) with ggtitle(as.character(k)) to ensure you're passing ggtitle a string.

like image 58
conor Avatar answered Oct 23 '25 05:10

conor


You could use paste(), example:

ggtitle(paste(your_value))
like image 34
cj23 Avatar answered Oct 23 '25 05:10

cj23



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!