Hi All,
I am having an issue with one part of my function. Ultimately I am building a custom chart output that allows the user to pass limited parameters, rather than needing to construct the plot each time. The issue I am having is when trying to limit the output legend to have only columns available in the data frame, rather than all colours identified in a list. The specific error is coming from scale_fill_manual(values = gsc_gender_colours[unique(.data${{gender_column}})])
which returns the following error:
Error: unexpected '{' in: " color = "#E4E4E5") + scale_fill_manual(values = gsc_gender_colours[unique(.data${"
What is the best way to:
- Limit the values displayed in a plot legend based on unique column values rather than a list of potential colours
OR - Pass an input parameter as a column when using
.data$
UPDATE
Reproducible Code
# Sample data frame with values
df <- data.frame(gender = c("Female", "Male"), count = c(628, 372))
# Colour list
gender_colours <- list(Female = "#006B35", Male = "#8DC63F", Undisclosed = "#B6B6B6")
# Custom function
create_headcount_gender_chart <- function(.data, headcount_column, gender_column){
.data %>%
ggplot2::ggplot() +
aes(x = 1.5, y = {{headcount_column}}, fill = {{gender_column}}) +
geom_bar(stat = "identity") +
coord_polar("y", start = 0) +
theme_void() +
xlim(0.2, 2.5) +
theme(legend.title = element_blank(),
legend.position = "bottom") +
geom_text(aes(label = paste(round({{headcount_column}} / sum({{headcount_column}}) * 100, 1), "%")),
position = position_stack(vjust = 0.5),
color = "#E4E4E5") +
scale_fill_manual(values = gender_colours[unique(.data[[gender_column]])])
}
# Testing the function
create_headcount_gender_chart(df,
count,
gender)
# Error from the function
Error in (function(x, i, exact) if (is.matrix(i)) as.matrix(x)[[i]] else .subset2(x, : object 'gender' not found