R 上 ggplot2 的 ggforce facet_zoom 错误

ggforce facet_zoom error with ggplot2 on R

我在 R 4.0.2 中有一个 data.frame,其中一列是连续变量,另一列是分类变量(变量 'type':已知或新颖)的两个可能值,我使用不同的颜色(使用 ggsci 2.9 包中的调色板)。我用 ggplot2 3.3.2 表示直方图 (stat_bin),我想使用 ggforce 0.3.2 的 facet_zoom 函数来仅缩放属于 'types' 之一的数据(使用选项 zoom.data,正如在 http://cran.univ-paris1.fr/web/packages/ggforce/vignettes/Visual_Guide.html#contextual-zoom 上的火山示例中所做的那样),但是我收到此错误:

Error: Aesthetics must be either length 1 or the same as the data (2000): x

可重现的例子:

library(ggplot2)
library(ggsci)
library(ggforce)

testdata <- as.data.frame(sort(rnorm(1000)))
testdata$type <- "known"
testdata[501:1000,2] <- "novel"

# Working code
ggplot(testdata) +
  stat_bin(aes(x=testdata[,1], fill = type), binwidth = 1, color="white") +
  scale_fill_npg() + theme_light() +
  facet_zoom(xlim = c(0, 4), ylim = c(0, 300), horizontal = TRUE, zoom.size = 0.3)

# Desired code
ggplot(testdata) +
  stat_bin(aes(x=testdata[,1], fill = type), data = cbind(testdata, zoom = FALSE), binwidth = 1, color="white") +
  stat_bin(aes(x=testdata[testdata$type == "novel",1]), data = cbind(testdata, zoom = TRUE), binwidth = 0.5) +
  scale_fill_npg() + theme_light() +
  facet_zoom(xlim = c(0, 4), ylim = c(0, 300), horizontal = TRUE, zoom.size = 0.3, zoom.data = zoom)

谢谢!

问题是您在第二个 stat_bin 中将整个数据集作为数据传递。只需传递子集 df 而不是尝试在 aes():

中进行子集化

顺便说一句:我还将您数据中的第一个变量重命名为 x。

library(ggplot2)
library(ggsci)
library(ggforce)

set.seed(42)

testdata <- data.frame(x = sort(rnorm(1000)))
testdata$type <- "known"
testdata[501:1000,2] <- "novel"

# Desired code
ggplot(testdata) +
  stat_bin(aes(x = x, fill = type), data = cbind(testdata, zoom = FALSE), binwidth = 1, color="white") +
  stat_bin(aes(x = x), data = cbind(testdata[testdata$type == "novel", ], zoom = TRUE), binwidth = 0.5) +
  scale_fill_npg() + theme_light() +
  facet_zoom(xlim = c(0, 4), ylim = c(0, 300), horizontal = TRUE, zoom.size = 0.3, zoom.data = zoom)

要在缩放图中仅显示 type == "novel" 数据,试试这个:

library(tidyverse)
library(ggsci)
library(ggforce)

testdata <- data.frame(values = sort(rnorm(1000)))
testdata$type <- "known"
testdata[501:1000,2] <- "novel"

# Desired code
ggplot(testdata) +
  stat_bin(aes(x = values, fill = type),
           binwidth = 1, color="white") +
  scale_fill_npg() + theme_light() +
  facet_zoom(zoom.data = ifelse(type == "novel", NA, FALSE), 
             xlim = c(0, 4), ylim = c(0, 300),
             horizontal = TRUE)