#' Make a butterfly plot
#'
#' @param sex 1 = Male, 2 = Female
#' @param age Age at diagnosis
#' @param vertical TRUE/FALSE, TRUE is a closed butterfly, FALSE horizonal overlapped density plot
#' @param title Plot title
#'
#' @import ggplot2
#' @importFrom dplyr case_when
#'
#' @return ggplot
#' @export
#'
#' @examples
#' butterfly_closed(malesFemales2010$sex, malesFemales2010$age, "Census 2010")
#' butterfly_closed(malesFemales2010$sex, malesFemales2010$age, "Census 2010", vertical=FALSE)
butterfly_closed <- function(sex, age, title = NULL, vertical = TRUE) {
sex <- as.character(sex)
sex[sex =="1"] <- "Male"
sex[sex == "2"] <- "Female"
Males <- data.frame(Males = age[sex == "Male"])
Females <- data.frame(Females = age[sex == "Female"])
statsMales <- summary(Males$Males)
statsFemales <- summary(Females$Females)
sex <- table(sex)
plot <-
ggplot() +
scale_x_continuous(breaks = c(0, seq(10, 110, by = 10))) +
scale_fill_manual(limits = c(" Male", " Female"),
values = c("#89cff0", "#FFC0CB")) +
theme_few() +
theme(
axis.text = element_text(size = 18),
axis.title = element_text(size = 18,
face = "bold"),
panel.grid.major.x = element_line(colour = "lightgray"),
panel.grid.major.y = element_line(colour = "lightgray"),
legend.title = element_blank()) +
scale_y_continuous(labels = NULL, name = "", limits = c(0, .05)) +
#scale_x_continuous(limits = c(0, 85), breaks = c(0, seq(20, 90, by = 10))) +
labs(x = "Age at Diagnosis\n", title = title ) +
guides(fill = guide_legend(
keywidth = .4,
keyheight = .4,
default.unit = "inch")
) +
expand_limits(x = c(0, 110))
if (nrow(Males) > 0){
plot <-
plot + geom_density(aes(x = Males, y = (..density..), fill = " Male"),
alpha = .5, data = Males, na.rm = TRUE)
}
if (nrow(Females) > 0){
plot <-
plot + geom_density(aes(x = Females, fill = " Female"),
alpha = .5, data = Females, na.rm = TRUE)
}
if (vertical == TRUE) {
plot <- plot +
coord_flip()
}
plot <- plot +
geom_abline(slope = 0, intercept = 0)
plot
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.