gpt4 book ai didi

r - 如何在 ggplot2 中正确使用 facet_grid?

转载 作者:行者123 更新时间:2023-12-03 11:37:21 24 4
gpt4 key购买 nike

我正在尝试使用以下代码为每个配置文件生成一个图表,但我不断收到“至少一层必须包含用于分面的所有变量”。错误。我花了最后几个小时试图让它工作,但我做不到。

我相信答案一定很简单,有人可以帮忙吗?

d = structure(list(category = structure(c(2L, 2L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L,
3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("4X4",
"HATCH", "SEDAN"), class = "factor"), profile = structure(c(1L,
1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L,
1L), .Label = c("FIXED", "FREE", "MOBILE"), class = "factor"),
value = c(6440.32, 6287.22, 9324, 7532, 7287.63, 6827.27,
6880.48, 7795.15, 7042.51, 2708.41, 1373.69, 6742.87, 7692.65,
7692.65, 8116.56, 7692.65, 7692.65, 7692.65, 7962.65, 8116.56,
5691.12, 2434, 8343, 7727.73, 7692.65, 7721.15, 1944.38,
6044.23, 8633.65, 7692.65, 7692.65, 8151.65, 7692.65, 7692.65,
2708.41, 3271.45, 3333.82, 1257.48, 6223.13, 7692.65, 6955.46,
7115.46, 7115.46, 7115.46, 7115.46, 6955.46, 7615.46, 2621.21,
2621.21, 445.61)), .Names = c("category", "profile", "value"
), class = "data.frame", row.names = c(NA, -50L))

library(ggplot2)

p = ggplot(d, aes(x=d$value, fill=d$category)) + geom_density(alpha=.3)
p + facet_grid(d$profile ~ .)

最佳答案

您的问题来自显式引用变量(即 d$profile ),而不是相对于 data调用 ggplot 中的参数.不需要d$任何地方。
faceting使用 facet_gridfacet_wrap ,你需要这样做。调用 aes 也是一种很好的做法。

p <- ggplot(d, aes(x = value, fill = category)) + geom_density(alpha = .3)
p + facet_grid(profile ~ .)
enter image description here

关于r - 如何在 ggplot2 中正确使用 facet_grid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16514930/

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