0

I have the following code for a density plot for the salary of men and women (sex is a variable coded as either 0 or 1):

GraphWageDensity<-  ggplot(df, aes(x = log(salary))) + 
  geom_line(stat= "density", aes(color =factor(sex), linetype=factor(sex)))  +
  geom_vline(data=mu1, aes(xintercept=grp.mean, color=factor(sex), 
                           linetype=factor(sex))) +
  theme_classic()  + labs(x="Log Monthly Wage", y="Density", col="Gender") +
  scale_color_discrete(labels = c("Women", "Men"), name="Gender") +
  scale_linetype_discrete(labels=c("Women", "Men"), name="Gender") +
  theme(axis.title.x = element_text(size=13),
        axis.title.y = element_text( size=13), 
        axis.text.x=element_text(color = "black", size=11), 
        axis.text.y=element_text(color = "black", size=11),
        legend.title = element_text(size = 15),
        legend.text = element_text( size = 15)) +
  geom_segment(aes(x = 10.1011, y = 0.025, xend = 10.23418, yend = 0.025)) +
  geom_text( x=10.17, y=0.1, label=("GPG \n 13.3%"), color="black",
             size=3.5)

  print(GraphWageDensity)

Now, whenever I print the graph, R automatically assign a red and blue colour to the two possible values of the factored sex. I would like to be able to choose what colours R will use, but as of now I have not been able to.

I tried something like:

colours_line<-matrix("black", nrow=35211)
colours_line[df$sex==1]<-"#3399FF"
lines<-matrix('dotdash', nrow=35211)
lines[df$sex==1]<-'solid'

colour_mean<-c("black", "#3399FF")
lines_mean<-c('dotdash', 'solid')

To substitute inside the relative options, but it doesn't make any difference, the colours will stay as the original one, just as the form of the lines (solid and dotted). Is there any way I can choose myself the colour of the densities? (I assume that, in the same way, I'll be able to choose also the type of lines).

Thank you so much in advance, and please do accept my apologises for the very noobish question!

Gabriele

  • 2
    I recommend reading into the great ggplot cookbook http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/ – tjebo Jan 28 '20 at 16:31

1 Answers1

2

Since you did not provide any dataframe, I will give you a toy example.

df2 <- data.frame(sex  = rep(c("Female", "Male"), each=3),
                  time = c("breakfeast", "Lunch", "Dinner"),
                  bill = c(10, 30, 15, 13, 40, 17))

ggplot(df2, aes(x=time, y=bill, group=sex)) +
            geom_line(aes(linetype=sex, color=sex))+
            geom_point(aes(color=sex))+
            scale_color_manual(values = c("red", "green"))

enter image description here

As you can see, you can change the colors with scale_color_manual.

eonurk
  • 507
  • 2
  • 12