Working from a solution posted elsewhere (ggplot2: text color based on background contrast), I've created a simple bar chart with labels that should be coloured white or black depending on the colour of the bar (i.e. white text for dark bars).
Firstly, I'm not sure that the code is working as intended, as white text is being used to label light-coloured bars. Secondly, the legend includes some of the code I've used for assigning colours.
Have you any suggestions to resolve these two issues? I've included an image of the chart for reference.
# Create a table of the proportions for use when creating the plot.
plotdata <- treatment_dataset %>%
group_by(STAGE, TREATMENT_GROUP) %>%
summarize(n = n()) %>%
mutate(pct = n/sum(n),
percentages = scales::percent(pct))
plotdata
# Plot the data from the table above
ggplot(plotdata,
aes(x = STAGE,
y = pct,
fill = TREATMENT_GROUP)) +
geom_bar(stat = "identity",
position = "fill") +
labs(y = "Proportion of tumours",
x = "Tumour stage at diagnosis",
fill = "Treatment group"
) +
scale_y_continuous(labels = scales::percent) -> treatment_by_stage
# Apply PHE formatting.
treatment_by_stage + theme_phe("phe") +
scale_fill_phe(name = "Treatment group",
theme = "phe") +
geom_text(aes(label = ifelse(pct < 0.05, NA, percentages), color = plotdata$pct > 0.01),
size = 3,
position = position_stack(vjust = 0.5)
) +
scale_color_manual(values = c("black", "white"))