【问题标题】:Appending list of values onto ggplots将值列表附加到 ggplots
【发布时间】:2021-05-11 00:07:00
【问题描述】:

我有一个值列表和一个 ggplots 列表。我想将列表中的值附加到 ggplots 上。有什么好办法吗?

这就是我所拥有的 ggplots 列表:

  p.list <- lapply(sort(unique(ind_steps$AnimalID)), function(i){
    ggplot(ind_steps[ind_steps$AnimalID == i,], aes(x = t2, y = NSD)) + 
      geom_line() + theme_bw() + 
      theme(axis.text.x = element_text(angle = 90)) +
      scale_x_datetime(date_breaks = '10 days', date_labels = '%y%j') +
      facet_grid( ~ AnimalID, scales = "free") +
      scale_colour_manual(values=hcl(seq(15,365,length.out=4)[match(i, sort(unique(ind_steps$AnimalID)))], 100, 65))
  })

假设我有另一个与这个长度相同的列表,并且每个列表中都有一个值。

我想将 ggplots 与值列表配对,并让值显示在每个相应的图中。我的预期输出是让值列表中的每个值都位于图列表中的每个相应图上。

【问题讨论】:

标签: r list ggplot2


【解决方案1】:

由于您在此处未提供任何示例数据,因此我使用 iris 内置数据集举了一个示例。您可以使用geom_text 或geom_label 向绘图添加值(如果我很了解您想要什么)。例如,这里我们将 R^2 值添加到列表中的所有绘图中:

library(ggplot2)
data(iris)
rsq <- lapply(1:length(unique(iris$Species)), function(i) {
  cor(iris[iris$Species == unique(iris$Species)[i], "Sepal.Length"], iris[iris$Species == unique(iris$Species)[i], "Petal.Length"])^2
})

p.list <- lapply(1:length(unique(iris$Species)), function(i) {
  ggplot(iris[iris$Species == unique(iris$Species)[i], ], aes(x = Sepal.Length, y = Petal.Length)) +
    geom_point() + theme_bw()+
    geom_text(aes(x=min(Sepal.Length),y=max(Petal.Length),label=paste0("R= ",round(rsq[[i]],2))))
})

library(gridExtra)
grid.arrange(p.list[[1]],p.list[[2]],p.list[[3]],nrow=3)

返回:

【讨论】:

    猜你喜欢
    • 2014-02-14
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2015-02-04
    • 2013-11-08
    • 1970-01-01
    相关资源
    最近更新 更多