r - R 中的 Swimmerplot,堆叠条之间有“空白”空间(ggplot)
问题描述
问题描述
我正在尝试使用 ggplot 在 R 中制作一个游泳图。但是,当我想在绘图的两个堆叠条之间留出“空白”空间时,我遇到了一个问题:这些条彼此相邻排列。
代码和示例数据
我有以下示例数据:
# Sample data
df <- read.table(text="patient start keytreat duration
sub-1 0 treat1 3
sub-1 8 treat2 2
sub-1 13 treat3 1.5
sub-2 0 treat1 4.5
sub-3 0 treat1 4
sub-3 4 treat2 8
sub-3 13.5 treat3 2", header=TRUE)
当我使用以下代码生成游泳图时,我最终得到了一个包含 3 个主题的游泳图。对象 2 仅接受了 1 次治疗(治疗 1),因此显示正确。
然而,受试者 1 接受了 3 次治疗:从时间点 0 到时间点 3 的治疗 1,然后从 3 到 8 什么都没有,然后从 8 到 10 的治疗 2 等等......
数据以某种方式绘制,在患者 1 和 3 中,所有治疗都是连续的,而不是中间有“空”间隔。
# Plot: bars
bars <- map(unique(df$patient)
, ~geom_bar(stat = "identity", position = "stack", width = 0.6,
, data = df %>% filter(patient == .x)))
# Create plot
ggplot(data = df, aes(x = patient,
y = duration,
fill = reorder(keytreat,-start))) +
bars +
guides(fill=guide_legend("ordering")) +
coord_flip()
问题
如何在这个游泳情节中包含两个非连续治疗之间的空白?
解决方案
在这种情况下,我认为这不是geom_bar
正确的几何。它实际上是为了显示频率或计数,您不能明确控制它们的开始或结束坐标。
geom_segment
可能是你想要的:
library(tidyverse)
# Sample data
df <- read.table(text="patient start keytreat duration
sub-1 0 treat1 3
sub-1 8 treat2 2
sub-1 13 treat3 1.5
sub-2 0 treat1 4.5
sub-3 0 treat1 4
sub-3 4 treat2 8
sub-3 13.5 treat3 2", header=TRUE)
# Add end of treatment
df_wrangled <- df %>%
mutate(end = start + duration)
ggplot(df_wrangled) +
geom_segment(
aes(x = patient, xend = patient, y = start, yend = end, color = keytreat),
size = 8
) +
coord_flip()
由reprex 包(v0.2.1)于 2019 年 3 月 29 日创建
推荐阅读
- javascript - 将 JSON 数据解析为 HTML 的有效方法
- sql-server - 基于文件的数据存储方法与数据库方法
- python - 将一对列表对象转换为包含重复项的字典
- java - Java如何改变静态参数的值
- java - 从 Swing 的对话框中删除取消按钮和“X”
- git - git push and pull over http 在 Windows 上挂起,没有错误
- c# - Razor Pages ASP.NET Core 缓存 onGet 属性
- javascript - 浏览器打开时每个选项卡或窗口上可用的存储变量
- python - 在python中缓存函数的最后k个结果
- scala - 如何在不破坏现有设置的情况下更改 akka-scala 响应模型