Skip to content

Instantly share code, notes, and snippets.

@MaximeWack
Created July 27, 2017 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaximeWack/b18f4d88c2e7ae9a37ecf9f3d1b16a88 to your computer and use it in GitHub Desktop.
Save MaximeWack/b18f4d88c2e7ae9a37ecf9f3d1b16a88 to your computer and use it in GitHub Desktop.
figures <- function(data, group = NULL)
{
if (is.null(group))
{
names(data) %>%
map(. %>%
{
ggplot(data) +
aes_(x = as.name(.)) -> g
if (is.factor(data[[.]]))
{
g <- g +
geom_bar() +
ylab("Nombre") +
theme(axis.text.x = element_text(angle = -45, vjust = 1, hjust = 0))
} else
{
g <- g +
geom_histogram(aes(y = ..density..)) +
geom_density() +
ylab("Proportion")
}
}) -> plots
names(plots) <- names(data)
plots
} else
{
names(data) %>%
map(. %>%
{
ggplot(data) +
aes_(x = as.name(.)) -> g
if (is.factor(data[[.]]))
{
g <- g +
geom_bar(aes_string(fill = group), position = "dodge") +
ylab("Nombre") +
theme(axis.text.x = element_text(angle = -45, vjust = 1, hjust = 0))
} else
{
g <- g +
aes_(fill = as.name(group)) +
geom_histogram(aes(y = ..density..), position = "dodge") +
geom_density(alpha = .5) +
ylab("Proportion")
}
}) -> plots
names(plots) <- names(data)
plots
}
}
save_figures <- function(plots, path)
{
dir.create(path, showWarnings = F, recursive = T)
names(plots) %>%
map( . %>% {ggsave(plot = plots[[.]], filename = str_c(path, str_replace_all(., "/", "-"), ".png"))})
}
df %>% figures -> figs_univarié
df %>% figures("grouping_variable") -> figs_par_groupe
figs %>% save_figures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment