在ggplot图例中保持我的数据排序,其中颜色和形状合并

时间:2017-09-24 10:12:15

标签: r ggplot2 legend

我正在制作一个情节,我需要在一个图例中混合名称,颜色和形状。 似乎传说按类名按字母顺序排列我的数据产生与我的类形状和颜色不匹配...我需要每个超类A,B,C具有唯一的形状所以我希望将A1,A2,A3作为三角形,并且B1 ,B2为圆圈。如何强制图例名称与我的数据中的颜色和形状的顺序相同? (我不想在图例中按字母顺序排列,这对我的实际应用程序毫无意义)

这是我的数据和代码:

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)

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)

Names in legend are ordered alphabetically not matching the order I specified in my data, so not matching my colors and shapes, and causing problem as I really need my legend items follows the same order as in my data.

如果我使用这个ggplot,名称与形状和颜色匹配,并且在图例中排列整齐,但现在它们与图中的点不匹配...

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

Now names in legend match shapes and colors as in my data, but now mismatch is in the plot x,y positions.

1 个答案:

答案 0 :(得分:1)

图例项目的顺序取决于定义图例的因子变量中的级别顺序。

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)

enter image description here

另一种方法是手动定义着色:

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))

enter image description here