gpt4 book ai didi

r - ggplot2 中 facet_grid 的图层无效

转载 作者:行者123 更新时间:2023-12-04 12:04:57 25 4
gpt4 key购买 nike

我一直在研究此代码的变体:

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 和数据帧处理矩阵的初始形式有关,但我不确定需要更改什么。

最佳答案

您的问题比facet_grid 更深远成分。

  • 矩阵只能容纳单一类型的数据。如果您有多种类型,请使用 data.frame .
  • as.doublefactor 强制转换的代码不正确至 numeric (根据需要,因为您强制使用了字符矩阵 --> data.frame。
  • ggplotaes应该引用列名,而不是使用 [ 的数据对象的直接子集.
  • 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

    关于r - ggplot2 中 facet_grid 的图层无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19917289/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com