【问题标题】:Adjusting legend.title ,legend.text and legend color in ggplot2调整ggplot2中的legend.title、legend.text和legend颜色
【发布时间】:2017-10-25 11:31:12
【问题描述】:

我无法更改图中分段图例的颜色。我需要两种不同的颜色作为图例和视觉图中的文本。

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

【问题讨论】:

  • 最简单的可能是添加+scale_color_continuous(name="Speed (m/s)\n")
  • 谢谢,但我遇到了错误。 + scale_color_continuous(name="Speed (m/s)\n") +scale_color_continuous(name = "Speed (m/s)\n") 中的错误:一元运算符的参数无效
  • 嗯,奇怪。您确定错误不会在您的代码中的其他地方发生,即当您省略 +scale_color_conti... 时是否会发生错误?
  • 顺便说一句,您应该根据答案更改原始问题的代码/输入。否则人们将无法理解问题应该解决的问题
  • 那是说“你应该...”:-)

标签: r ggplot2


【解决方案1】:

类似下面的东西应该可以工作。 只需明确指定图例标题并在字符串末尾添加\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")

【讨论】:

  • @Saara 太棒了!我还添加了第二个选项,这可能会有所帮助
  • 你知道如何更改分段图例颜色吗?
  • 但是我应该在哪里添加这个?
  • 只需在代码的第 2 行将 fill = Segmentation 替换为 col = Segmentation
  • 按点可视化步行/跑步也有点没有意义,因为您在整个片段中都这样做,使用geom_line(aes(col=SpeedMeterPerSecond), lty = Segmentation) 可能更有意义
猜你喜欢
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 2017-06-23
  • 2020-09-22
相关资源
最近更新 更多