【问题标题】:loop over groups and create plot for each one R循环组并为每个组创建图 R
【发布时间】:2018-09-13 15:45:19
【问题描述】:

我正在尝试对 Iris 数据集中的物种列进行映射/循环,以便为每个物种创建一个图。下面的脚本返回三个图表,但都绘制了相同的数据并且没有按物种划分。 map 函数似乎忽略了 species_list,只查看整个数据框。一直在尝试不同的方法,但无法正常工作。非常感谢任何帮助

干杯

library(ggplot2) 
library(purrr) 

species_list = unique(Iris$Species)

species_plot = function(x,y) {

     ggplot(data = Iris,colour = Species, aes_string(x=x,y=y)) + 
     geom_point(shape = 21, aes(fill = Species),colour = "black", size =8)

 }


species_bins = map(species_list, ~species_plot("sepal_length", "sepal_width") )

【问题讨论】:

  • 我想你的意思是iris
  • 为什么不直接使用分面?
  • 我希望将每个绘图导出到一个二进制文件中,我可以使用 lable 函数在地图上的 spotfire 中绘制该文件

标签: r


【解决方案1】:

试试这个:

# Load packages
library(tidyverse)
library(rlang)

# Define the function
species_plot <- function(x, y, pal = c('#2678B2', '#FD7F28', '#339F34')) {

    # Set variables to plot using the black magic of rlang
    x_var <- enquo(x)
    y_var <- enquo(y)

    # Generate plots
    iris_plots <- iris %>% 
        # Group and nest data by Species 
        # Creates a dataframe with two columns: 'Species' and 'data' (a list-column)
        group_by(Species) %>% 
        nest() %>% 
        # Add a new column with the ggplot objects
        mutate(plots = pmap(.l = list(data, pal, as.character(Species)), 
                            ~ ggplot(data = ..1) + # first element of .l
                                aes(x = !!x_var, # expose the x and y variables
                                    y = !!y_var) +
                                geom_point(shape = 21,
                                           size = 8,
                                           fill = ..2, # second element of .l
                                           colour = '#000000') +
                                labs(title = str_to_title(str_glue('{..3}'))) + # third element of .l
                                theme_bw() +
                                theme(legend.position = 'none')))

    # Walk through the plots column, printing each ggplot object
    walk(.x = iris_plots$plots,
         ~ print(.x))
}

# Test the function
species_plot(x = Sepal.Length, y = Sepal.Width)

reprex package (v0.2.0) 于 2018 年 9 月 13 日创建。

【讨论】:

    【解决方案2】:

    我们可以更改函数以包含“species_list”

    species_list <- unique(iris$Species)
    species_plot <- function(x,y, z) {
    
      ggplot(data = iris, aes_string(x=x,y=y, colour = z)) + 
         geom_point(shape = 21, aes_string(fill = z),
                   colour = "black", size =8)
    
      }
    
    map(species_list, ~species_plot("Sepal.Length", "Sepal.Width", .x) )
    

    【讨论】:

    • 您好,非常感谢您的回复和您的时间,我仍然无法得到我需要的东西。代码给了我三个图表,但是每个物种都绘制在每个图表上,我之后实现的是每个物种的单独图表。
    • berwyn72:我认为你错了,因为@akrun 的回答提供了 3 个单独的图表,每个图表一个物种
    猜你喜欢
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    相关资源
    最近更新 更多