使用 ggplot2 指定图例中的特定中断

specifying specific breaks in legend using ggplot2

library(raster)
library(dplyr)
library(ggplot2)

get.shapefile.df <- function(shp.in, df.in, 
 region.var){
 require(sf)
 require(sp)
 require(plyr)
 require(ggplot2)
 shp.in@data$id <- rownames(shp.in@data)
 shp.in@data   <- plyr::join(shp.in@data, df.in, 
 by=region.var)
 mapa.df     <- fortify(shp.in)
 mapa.df     <- plyr::join(mapa.df, shp.in@data, 
  by="id")
  return(mapa.df)
 }

mybound <- getData('GADM', country='FRA', level=1)
myShp <- getData('GADM', country='FRA', level=2)
temp <- data.frame(NAME_2 = myShp$NAME_2, 
                   value = sample(1:100, 96))

tempShp <- get.shapefile.df(myShp, temp, 'NAME_2')

ggplot() +
  geom_polygon(data = subset(tempShp, !is.na('value')), aes_string(x = 'long', y = 'lat', group = 'group', fill = 'value')) +
  geom_path(data = mybound, aes(long, lat, group = group)) + coord_equal() +
  scale_fill_viridis_c(limits = c(0, 100),option = 'D') +
  xlab(NULL) + ylab(NULL) +
  theme(plot.title = element_text(size = 8, face = "bold")) +
  theme(legend.title = element_blank(),
        legend.margin=margin(0,0,0,0), legend.box.margin=margin(-10,-10,-10,-10))

我的问题是我对分析罚款更感兴趣 1 到 10 之间的值如何分布的尺度模式。 我如何指定图例中的中断,例如:

 legendBrks <- c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30, 50, 100)

编辑

我最后做了这个

 temp$cuts <- cut(temp$value, 
                 breaks = c(-Inf, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30, 50, Inf), 
                 labels = c('0-1','1-2','2-3','3-4','4-5','5-6','6-7','7-8','8-9','9-10','10-15','15-20','20-30','30-50','50-100'))

tempShp <- get.shapefile.df(myShp, temp, 'NAME_2')

ggplot() +
 geom_polygon(data = subset(tempShp), 
           aes_string(x = 'long', y = 'lat', group = 'group', fill = 'cuts')) +
 geom_path(data = mybound, aes(long, lat, group = group)) + coord_equal() +
 viridis::scale_fill_viridis(name="", discrete=TRUE) +
 xlab(NULL) + ylab(NULL) +
 theme(plot.title = element_text(size = 8, face = "bold")) +
 theme(legend.title = element_blank(),
    legend.margin = margin(0,0,0,0), legend.box.margin = 
  margin(-10,-10,-10,-10))

您可以在 scale_fill_viridis_c() 中分配 breaks = legendBrks 但这会使您的图例难以阅读并且看起来不太好。

当我想检查大范围内分布不均的数据模式时,我会做什么 log-transform。这样,范围下端的微小差异变得更加明显。但是最简单的方法就是依靠 trans_breaks() 来打破你的传奇。

ggplot() +
  geom_polygon(data = subset(tempShp, !is.na('value')), aes_string(x = 'long', y = 'lat', group = 'group', fill = 'value')) +
  geom_path(data = mybound, aes(long, lat, group = group)) + coord_equal() +
  scale_fill_viridis_c(option = 'D', trans = "log2",  breaks = trans_breaks("log2", function(x) 2^x)) +
  xlab(NULL) + ylab(NULL) +
  theme(plot.title = element_text(size = 8, face = "bold")) +
  theme(legend.title = element_blank(),
        legend.margin=margin(0,0,0,0), legend.box.margin=margin(-10, 10,-10,- 10))

也许它也适合你的 pupros。