Do this:
# Create density plot with custom colors for categories A and B
ggplot(df, aes(x = x, y = y)) +
stat_density_2d(
aes(fill = cat, alpha = after_stat(level)),
geom = "polygon",
color = NA
) +
scale_fill_manual(
values = c("A" = "darkorange", "B" = "cyan2"),
name = "Category", # Legend title
guide = "legend"
) +
scale_alpha(range = c(0, 0.5), guide = "none")
refer this for colors.