遍历组并为每个R创建图

时间:2018-09-13 15:45:19

标签: r

我试图在Iris数据集中的物种列上进行地图绘制/循环,以为每个物种创建一个图。下面的脚本返回三个图表,但是所有图表都绘制了相同的数据,并且没有按种类划分。映射功能似乎忽略了物种列表,而只是查看整个数据框。一直在尝试各种方法,但无济于事。任何帮助表示赞赏

欢呼

if ( $usertype == "admin"){

        header("location:adminpage.php");

        } else  if ( $usertype == "user"){

        header("location: userpage.php");

        }

1 个答案:

答案 0 :(得分: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-09-13创建。