在ggplot2中调整legend.title,legend.text和图例颜色

时间:2017-10-25 11:31:12

标签: r ggplot2

我无法更改绘图中S​​egmentation图例的颜色。我需要两种不同的颜色作为图例中的文字以及视觉情节。

   er<-  ggmap(sq_map2) + 
   geom_point(data = sisquoc, size = 3,  aes(fill = Segmentation)) +
   geom_line(data = sisquoc, size = 3,  aes(color =SpeedMeterPerSecond)) +
   geom_text(data = sisquoc, aes(label = paste("  ", 
   as.character(Location_ids), sep="")), 
         angle = 60, hjust = 0, color = "sienna4",size = 6 ) 


   gg<- er  +   labs(x ="Longitude", y = "Latitude") +
   theme(axis.title = element_text(size=20), 
     panel.background = element_rect(fill = "white",size = 0.5, linetype = 
   "dotted"),
     panel.grid.major = element_line(size = 0.5, linetype = 'dotted',colour 
   = "black"), 
     panel.grid.minor = element_line(size = 0.5, linetype = 'dotted',colour 
   = "black"),
     panel.border = element_rect(colour = "black", fill=NA, size=0.5),
     axis.text.y   = element_text(size=18),
     axis.text.x   = element_text(size=18))

   gg  + theme(legend.position="right", 
         legend.title = element_text(colour="Black", size=18),
         legend.text = element_text(colour="black", size = 15),
         legend.background = element_rect(fill="grey90",
                                    size=0.5, linetype="solid", 
                                    colour ="black"))  + scale_color_continuous(name="Speed (m/s)\n")

1 个答案:

答案 0 :(得分:2)

以下内容应该有效。 只需明确指定图例标题,然后在字符串末尾添加\n,这会添加一个额外的空白行:

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, col=Petal.Length))+ 
  geom_point() + scale_color_continuous(name="my scale\n")

或者您也可以尝试更改图例方向 但是,当图例位于底部时,通常最紧凑。

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, col=Petal.Length))+ 
  geom_point() + theme(legend.direction = "horizontal", legend.position = "bottom")