ggplot2中facet_grid的图层无效。

4

我一直在使用这段代码的变体:

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]的基础上进行着色(在每个面板上为两种土壤类型生成一组点),并根据Compare[,4]生成三个面板。
当我在代码中包含facet_grid()时出现的错误是:
Error in layout_base(data, rows, drop = drop) : 
    At least one layer must contain all variables used for facetting

我觉得我的错误可能与将double和dataframe强制转换为处理矩阵的初始形式有关,但我不确定需要改变什么。


如果您为数据框的列命名并按名称引用它们,您将获得更好的效果。 - Ben Bolker
1
@BenBolker,我的完整代码中确实有它们的名称,但我选择删除名称,以尝试生成最短的可重现代码。将来,我会确保在发布时遵循这个惯例;是否值得编辑,还是保持不变作为对未来新手的警告? - hfisch
1个回答

5
您的问题不仅限于“facet_grid”组件:
1.矩阵只能保存单一类型的数据。如果您有多种数据类型,请使用"data.frame"。
2.“as.double”代码不能正确进行从“factor”到“numeric”的强制转换(因为您有一个字符矩阵强制转换 --> 数据框)。
3.“ggplot”和“AES”应该引用列名,而不是直接使用“[”子集的数据对象。
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 ~ . )

enter image description here


你的修复已经按照你指示的方式生成了三个面板(太棒了)。然而,看起来CP中的所有行都拾取了一个常数值(0, 0.379268)。 - hfisch
2
@renegade8191 - 我的笔误引用了原始矩阵Compare而不是数据框CP在因子->数值转换中。现已修复。 - mnel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接