ggplot geom_line plot difficulties

问题描述 投票:0回答:1

我有后续数据,想绘制每个受试者的药物使用情况。但是,当存在 NA 时,geom_line 不会中断线路。

# A tibble: 23 × 3
      ID   day medication
   <dbl> <dbl> <chr>     
 1     1     1 NA        
 2     1     2 A         
 3     1     3 NA        
 4     1     4 A         
 5     1     5 A         
 6     1     5 B         
 7     1     6 A         
 8     2     1 NA        
 9     2     2 C         
10     2     3 NA        
11     3     1 A         
12     3     2 C         
13     3     2 D         
14     3     3 D         
15     3     4 NA        
16     3     5 A         
17     4     1 C         
18     4     1 D         
19     4     2 C         
20     4     2 D         
21     4     3 C         
22     4     3 D         
23     4     4 NA


k<-df%>% ggplot() +
  geom_line(aes(x=day, y= medication ,color= medication, group=medication),linewidth = 1,) +
  facet_grid(ID~ ., drop = TRUE, scales = "free", space = "free")

方面 3 中的情节仍然包括药物 3 在不应该的地方。

我试图得到一张图表,其中最上面的一行表示随访(天),而当天使用的药物下面的所有行。

r ggplot2
1个回答
0
投票

不需要像Zhiqiang Wang建议的那样重新格式化数据
使用

geom_segment
调整 x 坐标以填充代表天数的单位段。缺失值由
na.omit
处理。

library(ggplot2)

ggplot(na.omit(df1)) +
  geom_segment(aes(x = day - 0.5, xend = day + 0.5, 
                   y = medication, yend = medication,
                color = medication), linewidth = 1) +
  facet_grid(ID~ ., drop = TRUE, scales = "free", space = "free")

创建于 2023-02-25 与 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.