1

我在 R 4.0.2 中有一个 data.frame,其中一列中有一个连续变量,另一列中有一个分类变量(变量“类型”:已知或新奇)的两个可能值,我用它们对它们进行不同的着色(使用调色板来自 ggsci 2.9 包)。我用 ggplot2 3.3.2 表示直方图(stat_bin),我想使用 ggforce 0.3.2 的 facet_zoom 函数仅缩放属于“类型”之一的数据(使用选项 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)

谢谢!

4

2 回答 2

0

问题是您将整个数据集作为第二个中的数据传递stat_bin。只需传递子集 df 而不是尝试子集 in 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)

于 2020-11-22T23:07:30.910 回答
0

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

例子.png

于 2020-11-22T23:09:54.393 回答