将形状、大小和颜色映射到 ggplot2 中的相同图例

Mik*_*kko 4 r ggplot2

我正在尝试在 ggplot 中绘制一个图形,其中颜色、形状和大小映射到变量,如下所示:0 值显示为红色十字。值 > 0 显示为圆圈,圆圈大小和颜色根据变量缩放(即圆圈越大,值越高)。我想使用分档的 viridis 比例来表示颜色。映射到颜色的值随机变化,因此缩放不应被硬编码。这是图:

library(tidyverse)

x <- tibble(x = sample(1:100, 10), y = sample(1:100, 10), z = c(0, sample(1:1e6, 9)))

color_breaks <- sort(unique(c(0, 1, pretty(x$z, n = 5), ceiling(max(x$z)))))

ggplot(x, aes(x = x, y = y, color = z, shape = z == 0, size = z)) +
  geom_point(stroke = 1.5) +
  scale_shape_manual(values = c(`TRUE` = 3, `FALSE` = 21), guide = "none") +
  scale_size(range = c(1, 8),
             breaks = color_breaks,
             limits = c(0, ceiling(max(x$z)))
  ) +
  binned_scale(aesthetics = "color",
               scale_name = "stepsn",
               palette = function(x) c("red", viridis::viridis(length(color_breaks) - 3)),
               limits = c(0, ceiling(max(x$z))),
               breaks = color_breaks,
               show.limits = TRUE
  ) +
  guides(color = guide_legend(), size = guide_legend()) +
  theme_bw()  
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2022 年 3 月 31 日创建(v2.0.1)

如何将变量组合到单个图例中,该图例应如下所示(在 Illustrator 中编辑)? 在此输入图像描述

All*_*ron 5

您可以覆盖里面的美学guides

x <- tibble(x = sample(1:100, 10), y = sample(1:100, 10), z = c(0, sample(1:1e6, 9)))

color_breaks <- sort(unique(c(0, pretty(x$z, n = 5)[-6], ceiling(max(x$z)) + 1)))

ggplot(x, aes(x = x, y = y, color = z, shape = z == 0, size = z)) +
  geom_point(stroke = 1.5) +
  scale_shape_manual(values = c(`TRUE` = 3, `FALSE` = 21), guide = "none") +
  scale_size(range = c(1, 8),
             breaks = color_breaks,
             limits = c(-1, ceiling(max(x$z)) + 2)
  ) +
  binned_scale(aesthetics = "color",
               scale_name = "stepsn",
               palette = function(x) c("red", viridis::viridis(length(color_breaks) - 1)),
               limits = c(-1, ceiling(max(x$z)) + 2),
               breaks = color_breaks,
               show.limits = FALSE
  ) +
  guides(color = guide_legend(),
         size = guide_legend(override.aes = list(shape = c(3, rep(16, 5))))) +
  theme_bw()  
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述