图例标题对齐 (ggmap)

Posted

技术标签:

【中文标题】图例标题对齐 (ggmap)【英文标题】:Alignment of Legend Title (ggmap) 【发布时间】:2020-12-18 18:05:05 【问题描述】:

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

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

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

这是我的代码:

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

【问题讨论】:

【参考方案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") 

【讨论】:

以上是关于图例标题对齐 (ggmap)的主要内容,如果未能解决你的问题,请参考以下文章

如何在 amcharts 图例中应用水平对齐?

将多图 ggplots 与拼凑和单个图例对齐

D3 左对齐图例文本

对齐多面图和图例

echarts图例中图标文字对齐

如何更改 Highchart 中图例的布局和对齐方式?