Reputation: 343
I want to generate a plot and stratify by sex. Unfortunately is my df coded in a way that males are red in the plot and females blue.
df <- data.frame(sex = rbinom(1000, 1, .5),
age = rnorm(1000, mean = 50, sd = 10))
df$sex <- as.factor(df$sex)
I can switch the colors with scale_color_manual but the bins have no fill and the outline isn't easy on the eye.
ggplot(df, aes(x = age, color = sex))+
geom_histogram(position = "identity")+
scale_color_manual(values = c("#00BFC4", "#F8766D"))
How to do it properly? Thanks in advance!
Upvotes: 0
Views: 319
Reputation: 126
If I understand your question correctly you can solve this by mapping sex to fill
.
df <- data.frame(sex = rbinom(1000, 1, .5),
age = rnorm(1000, mean = 50, sd = 10))
df$sex <- as.factor(df$sex)
ggplot(df, aes(x = age, fill = sex))+
geom_histogram(position = "identity")+
scale_fill_manual(values = c("#00BFC4", "#F8766D"))
After that you can switch the colors to match properly
Upvotes: 1
Reputation: 174293
I think you want to specify fill
instead of colour
in the aes
call, and use scale_fill_manual
instead of scale_colour_manual
. You get a better comparison of the two groups if you use position = "dodge"
too:
ggplot(df, aes(x = age, fill = sex)) +
geom_histogram(position = "dodge", colour = "black") +
scale_fill_manual(values = c("pink", "blue"))
Upvotes: 1