цикл по группам и создать сюжет для каждого R - PullRequest
0 голосов
/ 13 сентября 2018

Я пытаюсь нанести на карту / перебрать столбец видов в наборе данных Iris, чтобы создать график для каждого вида. Приведенный ниже скрипт возвращает три диаграммы, но все они имеют одинаковые данные и не разделены по видам. Функция карты, по-видимому, игнорирует список видов и просто просматривает весь фрейм данных. Я пытался по-разному подходить, но не мог заставить кого-либо работать. Любая помощь с благодарностью

Приветствия

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") )

Ответы [ 2 ]

0 голосов
/ 13 сентября 2018

Попробуйте это:

# 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)

Создано в 2018-09-13 пакетом Представить (v0.2.0).

0 голосов
/ 13 сентября 2018

Мы можем изменить функцию, добавив в нее «видов_списка»

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) )
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...