如何用ggplot2的facet_grid按Category为多变量点图添加横向分面
解决ggplot2中按Category分组feature的分面点图问题
这里直接给出修改后的完整代码,帮你实现按Category的A/B分组展示对应feature的点图:
library(ggplot2) # 加载你提供的数据集 test <- structure(list(fruit = structure(c(2L, 3L, 2L, 1L, 3L, 1L, 1L, 2L, 3L), .Label = c("potato", "tomato", "zucchini"), class = "factor"), value = c(1.79614067223751, 3.03886853214095, 1.64545172419968, 4.25443807208955, 5, 1.46068422675856, 5, 4.86348870541553, 2.89808116631958), feature = structure(c(3L, 5L, 5L, 5L, 1L, 4L, 2L, 2L, 2L), .Label = c("colour", "flavour", "length", "magic", "size"), class = "factor"), Ratio = c(0.00983606557377, 0.034188034188034, 0.013114754098361, 0.008383233532934, 0.051282051282051, 0.004790419161677, 0.011377245508982, 0.026229508196721, 0.034188034188034), Category = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("A", "B"), class = "factor")), class = "data.frame", row.names = c(NA, -9L)) # 修改后的绘图代码 p1 <- ggplot(data = test, aes(x = fruit, y = feature)) + geom_point(aes(size = Ratio, color = value, fill = value), stroke = 0.5, shape = 21) + guides(color = FALSE) + scale_fill_viridis_c() + # 核心:按Category创建分面,free_y让每个分面的y轴只显示当前分组的feature facet_grid(. ~ Category, scales = "free_y", space = "free_y") + # 优化分面标题样式(可选) theme(strip.background = element_rect(fill = "#f0f0f0"), strip.text = element_text(size = 12, face = "bold")) # 输出图形 print(p1)
关键细节说明:
- 分面语法:
facet_grid(. ~ Category)表示把Category作为列方向的分面(如果想把A/B放在上下两行,改成Category ~ .即可)。 - 自适应y轴:
scales = "free_y"和space = "free_y"是关键——因为A组的feature是length、size,B组是colour、magic、flavour,这两个参数会让每个分面只显示对应分组存在的feature,避免出现空的y轴标签,同时自动调整分面的垂直空间。 - 自定义分面标签:如果想让分面标题更直观(比如显示“Category A”而不是“A”),可以添加
labeller参数:
facet_grid(. ~ Category, scales = "free_y", space = "free_y", labeller = labeller(Category = function(x) paste("Category", x)))
这样就能得到你想要的按Category分组展示feature的点图啦。
内容的提问来源于stack exchange,提问作者mightaskalot
相关产品推荐
相关产品推荐

