我正在使用ggplot2使用以下代码和数据制作垂直散点图。我想为Wk42和Wk28添加一个中间条。对不起这个简单的问题,这是我与R的第一个周末。
ggplot(test, aes(x=Week, y=Score, color=PTID)) + geom_point(shape=1)
PTID Week Score
1 Subject 1 Wk42 NA
2 Subject 2 Wk42 0
3 Subject 3 Wk42 6
4 Subject 4 Wk42 NA
5 Subject 5 Wk42 NA
6 Subject 6 Wk42 78
7 Subject 7 Wk42 42
8 Subject 8 Wk42 NA
9 Subject 9 Wk42 38
10 Subject 10 Wk42 2
11 Subject 11 Wk42 4
12 Subject 12 Wk42 1
13 Subject 13 Wk42 NA
14 Subject 14 Wk42 NA
15 Subject 15 Wk42 17
16 Subject 1 Wk28 NA
17 Subject 2 Wk28 0
18 Subject 3 Wk28 11
19 Subject 4 Wk28 NA
20 Subject 5 Wk28 NA
21 Subject 6 Wk28 25
22 Subject 7 Wk28 28
23 Subject 8 Wk28 5
24 Subject 9 Wk28 33
25 Subject 10 Wk28 3
26 Subject 11 Wk28 0
27 Subject 12 Wk28 0
28 Subject 13 Wk28 NA
29 Subject 14 Wk28 NA
30 Subject 15 Wk28 11
谢谢!
答案 0 :(得分:0)
显然你需要做facetting来添加它。首先,您必须计算两组中的中位数并创建data.frame
。然后,您可以使用geom_hline
添加行。
library(dplyr)
data_hline <- data %>% group_by(Week) %>% summarize(Median = median(Score))
ggplot(test, aes(x=Week, y=Score, color=PTID)) + geom_point(shape=1) +
facet_wrap(~Week) + geom_hline(data=data_hline,aes(yintercept=Median))
这是一个可重现的例子
data_hline <- mtcars %>% group_by(cyl) %>% summarize(Median = median(mpg))
> ggplot(mtcars, aes(x=cyl,y=mpg,fill=as.factor(gear))) + geom_point()+
+ facet_wrap(~cyl,scales="free_x")+ geom_hline(data=data_hline,aes(yintercept=Median))
答案 1 :(得分:0)
诀窍是使用colour
中的geom_point
参数,这意味着在添加任何其他图层之前,数据尚未按主题分组。
ggplot(test, aes(x=Week, y=Score)) + geom_point(aes(colour = PTID), shape=1) +
stat_summary(aes(Week, Score), data = test, fun.data = "median_hilow", geom = "crossbar")