How to manually set colours to a categorical variables using ggplot()? [duplicate]

梦想的初衷 提交于 2019-12-04 06:06:02

问题


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?



来源:https://stackoverflow.com/questions/31515024/how-to-manually-set-colours-to-a-categorical-variables-using-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!