Barplot - 组合行

时间:2017-02-27 14:20:15

标签: r bar-chart

我想将这些数据用于绘图:

structure(c(15236000, 36722900, 8953800, 8975200, 45971100, 99067800, 
            20305100, 26360500, 91416000, 219396000, 71722610, 84034100, 
            230630600, 254380400, 52402800, 50422300, 354388700, 438443760, 
            72343800, 86587600, 462991400, 497156100, 51817210, 65168400, 
            235045400, 290932300, 41362400, 50220300, 168440600, 196797700, 
            107294900, 158465800, 362305500, 375372400, 158236400, 209906300, 
            1367158670, 1122186600, 220191000, 203426900, 978435120, 983735500, 
            373804400, 362937700, 2104276960, 2220253960, 394261700, 410656800, 
            1267607300, 1323143500, 285954000, 276834600, 1080187900, 1410693500, 
            1261120700, 1299253600, 840738200, 1226346700, 1591379300, 1829220400, 
            1139340100, 1758611700, 2003838200, 2346221200, 2425368000, 3150723500, 
            2658315400, 3184999800, 3141234200, 4124976700, 3484620300, 4132765100, 
            2880830100, 4403308600, 4233078100, 4962721300, 2923459800, 4360192600, 
            5238580300, 5647975300), .Dim = c(4L, 20L), .Dimnames = list(
              c("Mark_1", "Mark_2", "Chris_1", 
                "Chris_2"), c("15", "44", "49", "64", "109", 
                                              "114", "135", "156", "233", "264", "355", "465", "511", "561", 
                                              "612", "723", "858", "864", "922", "975")))

使用简单的barplot(data)我几乎可以得到我想要的情节。唯一的区别是我想在一个栏中没有4行组合,但是两个栏包含每行2行的数据。

如您所见,行名为Mark_1, Mark_2Chris_1, Chris_2。我想在一个柱子上放置Mark,在每个柱子的第二个柱子上放置Chris。很高兴在这个情节上看到一个很好的传奇。

1 个答案:

答案 0 :(得分:1)

您可以尝试:

dt <- cbind(rbind(data[1:2,], 0, 0), rbind(0, 0, data[3:4,])) 
dt <- dt[, order(as.numeric(colnames(dt)))]
n <- barplot(dt, axisnames = FALSE, las=1, offset = 0.1, col=1:4, space=c(0, rep(c(0,0.5), (ncol(dt)-2)/2), 0))
axis(1, at=(n[-length(n)] + diff(n)/2)[c(TRUE, FALSE)], labels = colnames(data), lwd = 0)
legend("topleft",legend = rownames(data), col=1:4, pch=15)

enter image description here

ggplot解决方案可能是:

library(reshape2)
library(stringr)
dl <- melt(data)
dl$Var3 <- unlist(lapply(str_split(dl$Var1, "_"), "[",1))
ggplot(dl, aes(y = value, fill=Var1, x=as.factor(Var2))) + geom_bar(stat = "identity") +
    facet_grid(~ interaction(Var3, Var2), scales = "free_x")+
    theme(panel.spacing.x= unit(0,"cm"),strip.text.x = element_blank(), strip.background = element_blank())