我的R有点生疏,我想知道如何制作分组直方图。我想做一个分组直方图,其中ratio.dis和ratio.opt分组为" name"。数据如下:
name total ratio.dis n ratio.opt
1 bass karen 13 2.000000 5 2.600000
2 braley 48 2.562500 16 3.000000
3 chu 18 2.166667 6 3.000000
4 cicilline 18 2.500000 6 3.000000
5 clinton 56 2.000000 18 3.111111
6 conyers 54 2.555556 18 3.000000
关于分组变量的所有其他教程使用ggplot和分组变量按" fill",但这不起作用,因为每个分类变量只有一个值。在直方图中,我希望创建," name"是X值,两个比率变量共享相同的y轴。我该怎么做?
答案 0 :(得分:1)
以下可能会有所帮助:
ddf = structure(list(name = c("bass.karen", "braley", "chu", "cicilline",
"clinton", "conyers"), total = c(13L, 48L, 18L, 18L, 56L, 54L
), ratio.dis = c(2, 2.5625, 2.166667, 2.5, 2, 2.555556), n = c(5L,
16L, 6L, 6L, 18L, 18L), ratio.opt = c(2.6, 3, 3, 3, 3.111111,
3)), .Names = c("name", "total", "ratio.dis", "n", "ratio.opt"
), class = "data.frame", row.names = c(NA, -6L))
ddf2 = melt(ddf[,c(1,3,5)], id='name')
ggplot(ddf2, aes(x=name, y=value, fill=variable))+geom_bar(stat='identity', position='dodge')
答案 1 :(得分:0)
一个(非常简单的)基础R解决方案:
dd <- structure(list(name = c("bass.karen", "braley", "chu", "cicilline",
"clinton", "conyers"), total = c(13L, 48L, 18L, 18L, 56L, 54L
), ratio.dis = c(2, 2.5625, 2.166667, 2.5, 2, 2.555556), n = c(5L,
16L, 6L, 6L, 18L, 18L), ratio.opt = c(2.6, 3, 3, 3, 3.111111,
3)), .Names = c("name", "total", "ratio.dis", "n", "ratio.opt"
), class = "data.frame", row.names = c(NA, -6L))
ddd <- cbind(dd$ratio.dis, dd$ratio.opt)
rownames(ddd) <- dd$name
barplot(t(ddd), beside = TRUE)
请注意,barplot
会返回每个条形图中心的位置,以便您可以执行
bp <- barplot(t(ddd), beside = TRUE)
text(bp, as.vector(t(ddd)) + 0.2, c("dis", "opt"), xpd = T)