如何仅使用 ggplot2 命令将连续变量“分解”为离散区间

wes*_*352 2 r ggplot2

我正在尝试用几何图形在 ggplot 中制作图表geom_sf。我可以使用 来绘制图表scale_fill_scontinuous,但是我想将标题分成离散的间隔,这样scale_fill_scontinuous我就可以使用 来代替使用scale_fill_brewer。\n我不想在 ggplot 之外创建中间 data.frame 或向量。

\n

目前我的图表如下所示:

\n
ggplot(data=uniao3, aes(fill=`\xc3\x81rea \xc3\x9amida`))+\n  geom_sf()+\n  scale_fill_continuous(limits=c(0,20000),\n                        breaks=c(500,2000,8000,15000,20000),\n                        labels=c(\'500\',\'200-2k\',\'2k-8k\',\'8k-15k\',\'15k>\'),\n                        name="Wetland")+\n    facet_wrap(~Ano)\n
Run Code Online (Sandbox Code Playgroud)\n

输出\n在此输入图像描述

\n

我希望将图例(比例)呈现为渐变,而不是呈现为类似于此的块:

\n

在此输入图像描述

\n

我知道该scale_fill_brewer命令非常优雅且高效地执行此操作,但是如何将连续变量设置为 ggplot 内的离散变量?

\n

scr*_*eri 5

我会选择scale_fill_stepsn,尽管评论中有多种其他解决方案。该函数负责根据您的需要离散化连续变量breaks,并且它允许使用colours向量中的任何颜色(而不仅仅是预先准备的调色板)。

另一个优点是中断和颜色向量的长度不需要匹配

获取一个sf对象

library(ggplot2)
library(sf)
#> Linking to GEOS 3.8.1, GDAL 3.2.1, PROJ 7.2.1

# get sf data
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
Run Code Online (Sandbox Code Playgroud)

使用scale_fill_stepsn

对于将连续数据切割成离散切片,这可能是最简单且最合适的方法。

# set breaks and colours
breaks <- seq(0, 0.3, by = 0.02)
breaks
#>  [1] 0.00 0.02 0.04 0.06 0.08 0.10 0.12 0.14 0.16 0.18 0.20 0.22 0.24 0.26 0.28
#> [16] 0.30

cols <- RColorBrewer::brewer.pal(9, "Spectral")
cols
#> [1] "#D53E4F" "#F46D43" "#FDAE61" "#FEE08B" "#FFFFBF" "#E6F598" "#ABDDA4"
#> [8] "#66C2A5" "#3288BD"

# plot
ggplot(data = nc, aes(fill = AREA)) +
  geom_sf() +
  scale_fill_stepsn(colours = cols,
                    breaks = breaks,
                    name = "area") +
  theme_minimal()
Run Code Online (Sandbox Code Playgroud)

请注意,为了清楚起见,我在调用外部分配了分隔符和列ggplot,但您当然可以直接在ggplot调用中指定它们。

使用scale_fill_brewer

这对于真实的离散数据来说更合适,但也适用于离散的连续数据。

在这里,您需要在设置比例之前自己进行切割。在调用中使用cutwith会将您的数字变量变成一个因子。breaksggplot2

使用 的颜色选择不太灵活scale_fill_brewer,因为您需要(?)使用现有的 RColorBrewer 调色板。

这样,颜色图例看起来与示例图例更相似,其中每个切口都被标记,而不是断点。

# plot
ggplot(data = nc, aes(fill = cut(AREA, breaks = seq(0, 0.3, by = 0.02)))) +
  geom_sf() +
  scale_fill_brewer(type = "qual",
                    # labels = labels, # if you must
                    palette = "Spectral",
                    name = "area") +
  theme_minimal()
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v2.0.1)于 2021-09-19 创建