【问题标题】:Unique axis labels with dplyr and ggplot - R具有 dplyr 和 ggplot 的唯一轴标签 - R
【发布时间】:2018-05-30 04:58:34
【问题描述】:

我正在使用purrr 制作多个ggplot2 绘图。如何使用数字字符串为每个 x 轴指定唯一名称?

我的最佳尝试(如下)只能获取字符串的第一个值,因此所有 3 个图表的 x 轴都显示为 1% explained variance,而我想要三个不同的名称 1% explained variance2% explained variance3% explained variance。谢谢

library(tidyverse)

new<-c(1,2,3)

iris%>%
  split(.$Species) %>%
  purrr::map2(.y = names(.),
              ~ ggplot(data=., aes(x=Sepal.Length, y=Sepal.Width))+
                geom_point()+
                labs(x=paste(round(new,2),'% explained variance', sep=''))
  )

【问题讨论】:

  • 看起来你使用的是 purrr 而不是 dplyr
  • 由于您已经创建了向量new,它与您的data.frames 列表的长度相同,您可以将其用作map2 中的第二个列表。因此,您的 map2 将类似于 %&gt;% map2(new, ~ggplot(...,而您的标签将是 x = paste( round(.y, 2)....y 指的是第二个列表中的元素)。

标签: r ggplot2 dplyr purrr


【解决方案1】:

map2 中,我们可以将.y 指定为seq_along(.),然后使用它来索引'new',因为'new' 是一个长度为3 的向量。

l1 <- iris %>% 
        split(.$Species) %>% 
        map2( seq_along(.), ~ 
             ggplot(data=., aes(x=Sepal.Length, y=Sepal.Width))+
                geom_point()+
                labs(x=paste(round(new[.y],2),'% explained variance', sep='')))

注意:如果我们不使用names,那么只需将“新”作为.y 传递(这里不使用list 元素的名称)


绘图可以保存为单个 pdf

library(gridExtra)
l2 <- map(l1, ggplotGrob)
ggsave(marrangeGrob(grobs = l2, nrow = 1, ncol =1), file = "plots.pdf")

或将其保存为单个 png,在同一页面上具有多个绘图

ggsave(marrangeGrob(grobs = l2, nrow = 3, ncol =1), file = "plots.png")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 2019-05-09
    • 2023-03-27
    • 2021-07-31
    相关资源
    最近更新 更多