You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言:使用purrr生成多ggplot2图时设置唯一X轴标签

解决purrr生成ggplot时X轴标签重复的问题

我来帮你搞定这个X轴标签重复的问题!

问题原因

你当前的代码里,new是一个长度为3的向量,但在labs(x=...)中直接调用new时,ggplot只会取这个向量的第一个元素作为X轴标签——因为labs()的参数需要单个字符串,而非向量。另外,你用map2时是把拆分后的物种数据和物种名称配对,并没有让new的每个元素和对应的图绑定起来。

解决方案

我们可以调整map2的输入,让它同时迭代拆分后的数据集和new向量,这样每个图都能拿到new中对应的数值:

library(tidyverse)

new <- c(1,2,3)

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

额外扩展(如果需要用到物种名称)

如果你还想给每个图加上物种名称作为标题,可以用pmap来同时迭代多个输入:

library(tidyverse)

new <- c(1,2,3)
species_labels <- names(split(iris, iris$Species))

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

这样每个图的X轴就会分别显示1% explained variance、2% explained variance和3% explained variance啦!

内容的提问来源于stack exchange,提问作者J.Con

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:07:23