我正在尝试映射/循环鸢尾花数据集中的物种列,为每个物种创建一个图。下面的脚本返回三个图表,但所有图表都绘制了相同的数据,并且不按物种划分。地图函数似乎忽略了species_list,只查看整个数据帧。一直在尝试不同的方法,但无法使任何工作发挥作用。非常感谢任何帮助
Cheers
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") )
尝试这个:
# 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)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)