r - 定义要在箱线图中绘制的箱/子组(来自连续变量)(R中的ggplot)
问题描述
以 iris 数据集为例,我想Sepal.Length
在 x 轴和Petal.Length
y 轴上绘制一个箱线图(仅适用于 setosa 物种)。然而,这首先需要将 x 轴的连续Sepal.Length
数据分组:Sepal.Length < 4.7, Sepal.Length 4.7 - 5, Sepal.Length 5 - 5.2 and Sepal.Length > 5.2.
其次,它需要将第一组和第三组分组在一起。我尝试了下面的代码,但这不起作用。任何建议,将不胜感激。谢谢你。
library(ggplot2)
bin1 <- iris[iris$Sepal.Length < 4.7, ]
bin2 <- iris[iris$Sepal.Length >=4.7 & <5, ]
bin3 <- iris[iris$Sepal.Length >=5 & <5.2, ]
bin4 <- iris[iris$Sepal.Length >=5.2, ]
binA <- bin1 + bin3
order <- c(bin2, binA, bin4)
ggboxplot(iris[iris$Species == "setosa", ], x="Sepal.Length", y="Petal.Length") + scale_x_discrete(limits=order)
解决方案
我会使用该cut
功能来做你正在做的事情。之后,您可以使用fct_collapse
修改您的切割点。您可以执行以下操作:
library(dplyr)
library(forcats)
library(ggplot2)
iris %>%
filter(Species == "setosa") %>%
mutate(sub_species = cut(Sepal.Length, breaks = c(-Inf, 4.7, 5, 5.2, Inf))) %>%
mutate(sub_species = fct_collapse(sub_species,
combined = c("(-Inf,4.7]", "(5.2, Inf]"))) %>%
ggplot(aes(sub_species, Petal.Length))+
geom_boxplot()
这会给你想要的。
或者,您可以替换cut
函数并使用dplyr
's case when 函数看起来像:
iris %>%
filter(Species == "setosa") %>%
# Case when to cases
mutate(sub_a = case_when( Sepal.Length < 4.7~"A",
Sepal.Length < 5~ "B",
Sepal.Length < 5.2~ "C",
TRUE~"D")) %>%
# Collapse A and D
mutate(collapsed = ifelse(sub_a %in% c("A", "D"), "combined", sub_a)) %>%
ggplot(aes(collapsed, Petal.Length))+
geom_boxplot()
在 OP 评论中,问题被扩展为包括创建其他几个子类。为了解决这个问题,我将使用该mutate
函数创建一些额外的子类别,然后使用该gather
函数将它们全部拉到一个列中,同时保留每个子类中的数据(例如保持计数正确)。
iris %>%
filter(Species == "setosa") %>%
# Case when to cases
mutate(sub_a = case_when( Sepal.Length < 4.7~"A",
Sepal.Length < 5~ "B",
Sepal.Length < 5.2~ "C",
TRUE~"D")) %>%
# Collapse A and D
mutate(collapsed1 = ifelse(sub_a %in% c("A", "C"), "A+C", sub_a)) %>%
mutate(collapsed2 = ifelse(sub_a %in% c("A", "C", "D"), "A+C+D", sub_a)) %>%
# Pull all the new categories together into a new column called subclass
gather(new_cat, subclass, sub_a:collapsed2) %>%
# Filter to desired
filter(subclass %in% c("B", "A+C", "D", "A+C+D")) %>%
ggplot(aes(subclass, Petal.Length))+
geom_boxplot()
推荐阅读
- docker - 如何在 nginx 容器中将环境变量与 lua 一起使用
- vue.js - 如何切换表中具有相同值的多行?
- python - 如何为 pos 增加价值?
- php - 删除 Hello Dolly 实际上会破坏我的 Wordpress 网站
- reactjs - React Ref's Deprecated - 什么是替代品?
- bash - Bash 变量编号按升序排列
- javascript - 如何将谷歌字体中的草书字体(字体名称中带有空格)包含到画布元素中
- laravel - 在 laravel 上使用本地 google 字体出现错误 404
- c++ - 在尝试使用 Windows 编译 lua 以使用 emscripten 时遇到障碍,“无法找到 ar rcu”
- python - 使用 unittest 在多输入函数中模拟 Python 输入