【问题标题】:Alignment of Legend Title (ggmap)图例标题对齐 (ggmap)
【发布时间】:2023-03-21 14:14:01
【问题描述】:

我正在尝试将图例标题移动到 ggmap 中的颜色栏(用于在 R 中使用 ggplot2 绘制地图的包)。我有两个问题:

  1. 如何让图例标题位于颜色栏的顶部(而不是左侧,如下所示)?

  2. 有没有办法让颜色条变长?

这是我的代码:

CenterOfMap <- geocode("41.396108,2.059348")
Ciutat_Map <- get_googlemap(c(lon=CenterOfMap$lon, lat=CenterOfMap$lat),
                            zoom = 11, maptype = "terrain", source = "google", color="bw", 
                            style=c(feature="all", element="labels",visibility="off"))

Ciutat_Map <- ggmap(Ciutat_Map, extent = "device")
Ciutat_Map <- Ciutat_Map + 
  geom_polygon(aes(x=long, y=lat, fill=TOTAL, group=group), 
               data=Hex_Grid_Pop_data, alpha =0.7) 
Ciutat_Map <- Ciutat_Map + 
  scale_fill_gradientn(colours = c("#e5d5f2", "#cdb4db", "#b293c2", "#9d78ad", 
                                   "#855a96", "#724485", "#5d2c70"), 
                       limits=c(0, 1700), oob=squish, space = "Lab", 
                       na.value = "transparent", guide = "colourbar")
Ciutat_Map <- Ciutat_Map + 
   theme(legend.position = c(0.90,0.1), 
         legend.direction = "horizontal", 
         legend.title = element_text(size = 16), 
         legend.text = element_text(size = 14)) + 
   labs(fill = "Total Population") 

Ciutat_Map

【问题讨论】:

    标签: r ggplot2 ggmap


    【解决方案1】:

    您可以将scale_fill_gradientn() 中的guide = "colourbar" 替换为更详细的规格:

    guide = guide_colourbar(title.position = "top", # this changes legend title position
                            barwidth = 20)          # adjust as needed
    

    使用随机生成的数据进行说明:

    set.seed(123)
    df <- data.frame(
      x = runif(100),
      y = runif(100),
      z = runif(100, 0, 1700)
    )
    
    ggplot(df, aes(x, y)) +
      geom_point(aes(fill = z), shape = 21) +
      scale_fill_gradientn(colours = c("#e5d5f2", "#cdb4db", "#b293c2", "#9d78ad", 
                                       "#855a96", "#724485", "#5d2c70"), 
                           limits=c(0, 1700), oob=scales::squish, space = "Lab", 
                           na.value = "transparent", 
                           guide = guide_colorbar(title.position = "top",
                                                  barwidth = 20)) + 
      theme(legend.position = c(0.90,0.1), 
            legend.justification = c(1,0),
            legend.direction = "horizontal", 
            legend.title = element_text(size = 16), 
            legend.text = element_text(size = 14)) +
      labs(fill = "Total Population") 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      相关资源
      最近更新 更多