ggplot2图形标题基于for循环变量的迭代 [英] ggplot2 plot title based on an iterating for loop variable

查看:52
本文介绍了ggplot2图形标题基于for循环变量的迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用要在for循环中迭代的变量(k)为每个图加上标题:

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()

当对 ggtitle()使用字符串(例如: ggtitle("Name"))或删除 ggtitle()完全

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

关于如何将迭代器变量(k)的值作为每个图的标题的建议?

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

推荐答案

MyData $ Name中的数据是什么类?

What class are the data in MyData$Name ?

尝试将 ggtitle(k)替换为 ggtitle(as.character(k)),以确保您传递的是 ggtitle 一个字符串.

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

这篇关于ggplot2图形标题基于for循环变量的迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆