R 创建一个棒棒糖图表来比较组
我有以下数据框R 创建一个棒棒糖图表来比较组,r,dataframe,ggplot2,R,Dataframe,Ggplot2,我有以下数据框 library(ggplot2) set.seed(149) x <- data.frame( region = factor(rep(1:10, each = 2)), group = rep(c("O", "E"), 10), mean = sample(1:2, 20, replace = TRUE) ) x region group mean 1 1 O 2 2 1 E 1 3
library(ggplot2)
set.seed(149)
x <- data.frame(
region = factor(rep(1:10, each = 2)),
group = rep(c("O", "E"), 10),
mean = sample(1:2, 20, replace = TRUE)
)
x
region group mean
1 1 O 2
2 1 E 1
3 2 O 1
4 2 E 2
5 3 O 1
6 3 E 1
7 4 O 1
8 4 E 1
9 5 O 1
10 5 E 2
11 6 O 2
12 6 E 2
13 7 O 1
14 7 E 1
15 8 O 1
16 8 E 1
17 9 O 1
18 9 E 2
19 10 O 1
20 10 E 1
基本上,对于每个区域,我想画两条线,一条为“O”组,一条为“E”组。我们可以通过使用
geom\u linerange
(“棍子”)、geom\u point
(“糖果”)和指定位置=位置\u道奇来实现这一点:
ggplot(x)+
geom_linerange(aes(x = region, ymin = 0, ymax = mean, colour = group),
position = position_dodge(width = 1))+
geom_point(aes(x = region, y = mean, colour = group),
position = position_dodge(width = 1))+
coord_flip()
刻面也可以完成任务,当您有一系列类别(即不只是两个类别,而是4、6等)时,刻面可能特别有用
ggalt包装中有一个geom_棒棒糖
。
ggplot(x)+
geom_linerange(aes(x = region, ymin = 0, ymax = mean, colour = group),
position = position_dodge(width = 1))+
geom_point(aes(x = region, y = mean, colour = group),
position = position_dodge(width = 1))+
coord_flip()
ggplot(x, aes(y = region, x = mean, label = mean, fill = group, colour = group)) +
geom_segment(aes(x = 0, y = region, xend = mean, yend = region), color = "grey50", size = 0.75) +
geom_point(size = 3) +
facet_wrap(~group)