在 geom_sf 中向颜色条图例添加逗号(R ggplot)

add commas to colorbar legend in geom_sf (R ggplot)

我正在使用 ggplot 和 geom_sf 制作地图,我想在图例中的值中添加逗号。我发现编辑颜色条的唯一方法是通过 "guides",但 + guides(fill = guide_colorbar(labels="comma")) 似乎没有做任何事情(可能是因为 "labels" 不是 [=20] 中包含的规范=]?) 我如何获得一个相同的图例,其中包含数字超过 1,000 的逗号?

获取所有数据的代码有点长,所以我希望有人不用 reprex 就知道答案,但如果需要我可以编辑它。谢谢!

landingsmap <- ggplot() + 
  scale_x_continuous(limits=c(-126, -116), expand=c(0,0)) + 
  scale_y_continuous(limits=c(32, 42), expand=c(0,0)) + 
  geom_sf(data=simpleblocks, aes(colour=number_fish, fill=number_fish)) + 
  scale_colour_gradient(low="lightcoral", high="darkred", name="Number of Fish") + 
  scale_fill_gradient(low="lightcoral", high="darkred", name="Number of Fish") +
  geom_sf(data=camap, colour="black") + 
  theme(
    panel.background = element_rect(fill="skyblue4", size=0.5, linetype="solid"),
    legend.position = c(0.78, 0.5)
    ) + 
  NULL
landingsmap 

试试这个。我将使用 sf 包中的示例。

library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.1.3, proj.4 4.9.3
library(ggplot2)
fname <-  system.file("shape/nc.shp", package = "sf")
nc <-  read_sf(fname)

ggplot(nc)+
  geom_sf(aes(fill = BIR79))+
  scale_fill_continuous(labels=function(x) format(x, big.mark = ",", scientific = FALSE))

reprex 创建于 2018-09-19 包 (v0.2.0).

因此,对于您的示例,您可以这样写:

scale_fill_gradient(low="lightcoral", high="darkred", name="Number of Fish", labels=function(x) format(x, big.mark = ",", scientific = FALSE))

尝试使用 scales::comma 如下:

scale_fill_gradient(label = scales::comma)