r - R ggspot2中并排的箱线图和绘图点
问题描述
所以我有一个数据集(下面的输出),我的目标是让箱线图和图并排。 (见下图)
library(tidyverse)
DataSet <- read.csv("filelocation")
ggplot(data = DataSet,
aes(x = id,
y = result)) +
geom_boxplot(aes(color = live)) +
facet_wrap( ~ resource, scales = "free_y")
例如,对于这个数据集,c3 将有一个表示 True 的箱线图,但在它的右侧,有一个表示 False 的绘图点。
输入输出:
structure(list(id = c(101L, 101L, 101L, 101L, 102L, 102L, 102L,
102L, 103L, 103L, 103L, 103L, 103L, 103L, 103L, 104L, 104L, 104L,
104L, 104L, 105L, 106L, 106L, 106L, 106L, 106L, 107L, 107L, 107L,
107L, 108L, 108L, 109L, 109L, 109L, 109L, 109L, 109L, 109L, 109L,
109L, 109L), resource = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L), .Label = c("a", "b"), class = "factor"), result = c(2.12,
4.72, 4.17, 5.53, 3.6, 3.31, 3.64, 5.33, 4.32, 5.48, 5.93, 3.4,
3.09, 5.91, 2.93, 1.81, 3.93, 2.22, 4.77, 3.92, 4.08, 3.65, 5.23,
3.74, 4.03, 3.54, 4.29, 4.3, 2.82, 2.89, 5.41, 4.61, 4, 5.92,
1.66, 1.65, 1.91, 2.69, 5.28, 2.24, 3.64, 4.77), live = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L), .Label = c("f", "t"), class = "factor")), class = "data.frame", row.names = c(NA,
-42L))
理想情况下,我还希望能够用分界线分隔组,如图所示。我已经阅读了一些 R 资源,但没有看到任何可以完成的提示。
解决方案
如果我正确理解您的问题,您想使用箱线图来显示TRUE
值,并使用点来显示(少数)FALSE
值,并且您想根据resource
.
我将使用您问题中当前显示的数据,@Richard Telford 已经清理了这些数据。
使用 facet_wrap()
我们将使用subset()
的值来拆分您的数据live
。TRUE
行使用箱线图绘制,FALSE
行使用点绘制。我分别为每个组使用了绿色和红色,但您可能想要更改它。
ggplot() +
geom_boxplot(data = subset(cleanData, live == 't'),
aes(x = id, y = result, group = resource), color = 'green') +
geom_point(data = subset(cleanData, live == 'f'),
aes(x = id, y = result), color = 'red', size = 3) +
facet_wrap( ~ resource, scales = 'fixed') +
scale_x_continuous(breaks = c(101:109), minor_breaks = NULL)
没有 facet_wrap()
根据您设置scales
网格的方式,您最终可能会得到很多空白空间(正如我们在上图中所做的那样)。下面的代码不使用facet_wrap()
,而是使用带有垂直线的单个图,该垂直线大约将变量的a
和b
值resource
相除。
ggplot() +
geom_boxplot(data = subset(so.data, live == 't'),
aes(x = id, y = result, group = resource), color = 'green') +
geom_point(data = subset(so.data, live == 'f'),
aes(x = id, y = result), color = 'red', size = 3) +
scale_x_continuous(breaks = c(101:109), minor_breaks = NULL) +
geom_vline(xintercept = 104.15, linetype = 'dashed')
希望这能让你走上正轨,准确地找出你想要的东西。
推荐阅读
- haskell - 为什么使用 Maybe 时 catch 不能正确调用处理程序?
- google-sheets - 仅使用公式将一维数组拆分为二维数组
- pytorch - 水平翻转数据的不同性能
- javascript - 如果至少一个项目没有应用特定样式,则执行某项操作
- c++ - 滚动背景图像,无法隐藏接缝,c ++ raylib
- c# - 为什么我在 Driver.FindElementsByCssSelector() 检索到的元素上得到 StaleElementReferenceException;
- sql - 检查日期是否等于其各自季度的最后一天
- vb.net - 仅从文件夹中获取完整路径,而不以 c:\ 开头
- powershell - 排序对象名称未返回预期的顺序
- html - 为什么我的 Bootstrap 导航栏无法正常显示?