【问题标题】:Invalid layers for facet_grid in ggplot2ggplot2 中 facet_grid 的层无效
【发布时间】:2013-11-11 22:32:52
【问题描述】:

我一直在处理此代码的变体:

library(ggplot2)

Compare = matrix(c(
0,           0,           "Soil 1", "tF",
0.379268025, 5.555806214, "Soil 1", "tF",
0.961561989, 13.05580621, "Soil 1", "tF",
1.55418685,  20.55580621, "Soil 1", "tF",
0,           0,           "Soil 2", "tF",
0.104297312, 1.581249799, "Soil 2", "tF",
0.705818262, 6.081249799, "Soil 2", "tF",
1.447379092, 10.5812498,  "Soil 2", "tF",
0,           20,          "Soil 1", "tf",
0.379268025, 13.1603086,  "Soil 1", "tf",
0.961561989, 12.72354396, "Soil 1", "tf",
1.55418685,  12.60549558, "Soil 1", "tf",
0,           20,          "Soil 2", "tf",
0.104297312, 10.51383279, "Soil 2", "tf",
0.705818262, 6.433709727, "Soil 2", "tf",
1.447379092, 5.82398083,  "Soil 2", "tf",
0,           0,           "Soil 1", "zf",
0.379268025, 205.7706005, "Soil 1", "zf",
0.961561989, 483.5483783, "Soil 1", "zf",
1.55418685,  761.3261561, "Soil 1", "zf",
0,           0,           "Soil 2", "zf",
0.104297312, 23.25367352, "Soil 2", "zf",
0.705818262, 89.43014411, "Soil 2", "zf",
1.447379092, 155.6066147, "Soil 2", "zf"), nrow = 24, ncol = 4, byrow = TRUE)

plot = ggplot(as.data.frame(Compare),
aes(as.double(Compare[,1]), as.double(Compare[,2]), color = Compare[,3])) +
    geom_point() + facet_grid(Compare[,4] ~ .)
plot

我的问题是代码的facet_grid() 方面。如果我将其注释掉或删除它,它运行得很好,所以我知道我可以将我的问题隔离到与它有关的事情上。我想要完成的是一组垂直堆叠的三个面板,Compare[,1] 在 x 轴上,Compare[,2] 在 y 轴上,基于Compare[,3] 的着色(为两种土壤生成一组点每个 facet 上的类型),以及根据Compare[,4] 产生的三个 facet。

当我使用代码中包含的facet_grid() 运行时得到的错误是:

Error in layout_base(data, rows, drop = drop) : 
    At least one layer must contain all variables used for facetting

我觉得我的错误可能与强制双精度数和数据帧处理矩阵的初始形式有关,但不确定需要更改什么。

【问题讨论】:

  • 如果您为数据框的列命名并按名称引用它们,情况会好得多。
  • @BenBolker,我确实在我的完整代码版本中命名了它们,但选择删除名称以尝试生成最短的可重现代码。以后发帖一定要遵守这个约定;是否值得编辑,还是我将其保留为对未来新手的警告?

标签: r ggplot2


【解决方案1】:

您的问题比facet_grid 组件更深远。

  1. 矩阵只能保存一种类型的数据。如果您有多种类型,请使用data.frame
  2. 您的 as.double 代码对于从 factor 强制转换为 numeric 不正确(因为您强制转换了字符矩阵 --> data.frame。
  3. ggplotaes 应该引用列名,而不是使用 [ 的数据对象的直接子集。
  4. facet_grid 更特别需要names,甚至没有它的功能。

所以,拯救你的数据。

CP <- as.data.frame(Compare)

CP[[1]] <- as.numeric(as.character(CP[[1]]))
CP[[2]] <- as.numeric(as.character(CP[[2]]))
# your data.frame names are..
names(CP)
# [1] "V1" "V2" "V3" "V4"

ggplot(CP, aes(x = V1, y = V2, colour = V3)) +
 geom_point() + facet_grid(V4 ~ . )

【讨论】:

  • 您的修复程序会生成三个面板,正如您所指出的(太棒了)。但是,CP 中的所有行似乎都获得了一个恒定值 (0, 0.379268)。
  • @renegade8191 - 我的错字在因子-> 数字转换中引用了原始矩阵 Compare 而不是 data.frame CP。现已修复。
猜你喜欢
  • 2013-03-29
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多