首页 > 解决方案 > 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 资源,但没有看到任何可以完成的提示。

标签: rggplot2

解决方案


如果我正确理解您的问题,您想使用箱线图来显示TRUE值,并使用点来显示(少数)FALSE值,并且您想根据resource.

我将使用您问题中当前显示的数据,@Richard Telford 已经清理了这些数据。

使用 facet_wrap()

我们将使用subset()的值来拆分您的数据liveTRUE行使用箱线图绘制,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

没有 facet_wrap()

根据您设置scales网格的方式,您最终可能会得到很多空白空间(正如我们在上图中所做的那样)。下面的代码不使用facet_wrap(),而是使用带有垂直线的单个图,该垂直线大约将变量的abresource相除。

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')

相同的情节

希望这能让你走上正轨,准确地找出你想要的东西。


推荐阅读