图例标题的对齐方式(ggmap)

时间:2020-08-30 11:26:25

标签: r ggplot2 ggmap

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

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

  2. 是否可以使颜色条更长?

image

这是我的代码:

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 个答案:

答案 0 :(得分:2)

您可以用更详细的规范替换guide = "colourbar"中的scale_fill_gradientn()

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

plot