How to manually set colours to a categorical varia

2019-03-04 17:54发布

问题:

This question already has an answer here:

  • Manually setting group colors for ggplot2 1 answer

This is my sample data

table1
   xaxis    yaxis                  ae        work
1      5    35736 Attending_Education     Working
2      6    72286 Attending_Education     Working
3      7   133316 Attending_Education     Working
4      8   252520 Attending_Education     Working
5      9   228964 Attending_Education     Working
6     10   504676 Attending_Education     Working

This is the code i had used.

p<-ggplot(table1,aes(x=table1$xaxis,y=table1$yaxis))

Economic_Activity<-factor(table1$work)
Education_Status<-factor(table1$ae)

p<-p+geom_point(aes(colour=Education_Status,shape=Economic_Activity),size=4)
p+xlab("Population Ages")+ylab("Attending Education Institutions Count")+ggtitle("Attending Educational Institutions by Economic Activity Status :: INDIA 2001")

This is the output i got.

I Wish to do two things in this graph.

  1. i wish to set color manually to this categorical variables (Attending_Education\Not_AE). For example. Dark Green color for Attending_Education and red color for Not_AE.

  2. In the legend of economic activity, i don't need black color for working\not_working category. i need the Dark green and red color.

iam new to R. i had tried palette() too found @ below link. but nothing seems to work How to assign specfic colours to specifc categorical variables in R?

Note: please look at my requirements.

 Categories           Attending_Education			Not_AE
Working		Green color\Round Shape		Red Color\Round shape
Not_Working	Green color\Triangle Shape	Red Color\Triangle shape

Your help is appreciated. Thanking u all.

回答1:

For your first question, you need to use scale_colour_manual:

p +
  xlab("Population Ages") +
  ylab("Attending Education Institutions Count") +
  ggtitle("Attending Educational Institutions by Economic Activity Status :: INDIA 2001") +
  scale_colour_manual(values = c("Attending_Education" = "dark green", "Not_AE" = "red"))

For your second, I'm not clear what you want. Economic activity is represented as shape, not colour. So what would be the meaning of having dark green/red colours within that legend?