Keep ordering of my data in ggplot legend where color and shape are combined

只愿长相守 提交于 2019-12-04 14:32:58

The order of the legend items depends on the level order in the factor variable defining the legend.

library(ggplot2)
    x<-c(1,2,3,4,5,6,7,8,9)
    y<-c(1,1,2,2,2,3,3,3,3)
    classNames<-c("B1","B2","A1","A2","A3","C1","C2","C3","C4")
    classColors<-c("darkorange","darkorange3","cyan","blue","blue4","green1","green2","green3","green4")
    classShapes<-c(1,1,2,2,2,3,3,3,3)

datadf<-data.frame(x,y,classNames,stringsAsFactors = FALSE)
#defining the levels:
datadf$classNames <- factor(datadf$classNames, levels = classNames)


ggplot()+
  geom_point(data=datadf,aes(x=x,y=y,shape=classNames,color=classNames))+
  scale_color_manual(name="My classes",values = classColors)+
  scale_shape_manual(name="My classes",values = classShapes)

another approach is defining the coloring manually:

ggplot()+
  geom_point(data=datadf,aes(x=x,y=y,shape=classNames,color=classNames))+
  scale_color_manual(name="My classes",values = c("A1" = "blue", "A2" = "red", "A3" = "orange", "B1" = "brown", "B2" = "black", "C1" = "grey50", "C2" = "pink", "C3" = "lightblue", "C4" = "green"))+
  scale_shape_manual(name="My classes",values= c("A1" = 1, "A2" = 2, "A3" = 3, "B1" = 4, "B2" = 5, "C1" = 6, "C2" = 7, "C3" = 8, "C4" = 9))

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