2

I'm making a map using ggplot and geom_sf and I want to add commas to the values in the legend. The only way I've found to edit a color bar is through "guides", but + guides(fill = guide_colorbar(labels="comma")) doesn't seem to do anything (maybe because "labels" is not a specification included in "guides"?) How do I get an identical legend that includes commas in numbers over 1,000?

The code to get all the data is a little long so I'm hoping someone knows the answer without a reprex, but I can edit it in if needed. Thanks!

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 

enter image description here

AFH
  • 665
  • 1
  • 9
  • 28
  • Yes, a reprex is indeed always better... the map does not really matter. Most of your code is not really needed for this issue. The question is about putting commas into your legend. you can also create an example based on any data frame with continuous variables such as `diamonds` or `iris`... just a suggestion. – tjebo Sep 19 '18 at 20:25
  • 1
    https://stackoverflow.com/a/15007117/7941188 might help. The idea is to specify `labels = comma` in the `scale_gradient` call, but @AndS. answer which just popped in seems great – tjebo Sep 19 '18 at 20:32

2 Answers2

6

Try this. I'll use an example from the sf package.

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

Created on 2018-09-19 by the reprex package (v0.2.0).

So, for your example, you would write:

scale_fill_gradient(low="lightcoral", high="darkred", name="Number of Fish", labels=function(x) format(x, big.mark = ",", scientific = FALSE))
AndS.
  • 7,748
  • 2
  • 12
  • 17
1

Try using scales::comma as follows:

scale_fill_gradient(label = scales::comma)
ELmono
  • 11
  • 1