使用多个数据框架绘制彼此相邻的条形图

时间:2017-06-10 17:43:45

标签: r dataframe ggplot2 bar-chart

我想在彼此旁边绘制不同的条形图,但是我收到以下错误消息:

"轴错误(if(horiz)2 else 1,at = at.l,labels = names.arg,lty = axis.lty,:formal argument" at"匹配者多个实际参数"

我该如何解决这个问题?

此示例中的数据为:

structure(c(2L, 9L, 1L), .Dim = c(3L, 1L), .Dimnames = list(c("Positiv.26", 
    "Negativ.26", "Keine.26"), NULL))

structure(c(11L, 17L, 11L), .Dim = c(3L, 1L), .Dimnames = list(
        c("Positiv.45", "Negativ.45", "Keine.45"), NULL))

structure(c(17L, 15L, 7L), .Dim = c(3L, 1L), .Dimnames = list(
                c("Positiv.85", "Negativ.85", "Keine.85"), NULL))

这是我到目前为止所拥有的;

barplot((Histo.26[1:3,]), ylim= c(0,20), xlim = c(0,10), col=c("red","lightblue","gray"), 
        beside = T, xaxt="n")

barplot((Histo.45[1:3,]), at =c(4,5,6), col=c("red","lightblue","gray"), 
        xaxt="n", add=TRUE)

barplot((Histo.85[1:3,]), at =c(7,8,9), col=c("red","lightblue","gray"), 
        xaxt="n", add=TRUE)


axis(1, at = c(2,5,8), labels = c("Group1","Group2","Group3") , tick=FALSE , cex=0.3) 

2 个答案:

答案 0 :(得分:1)

您是否有理由不将数据合并到一个列表中:

L <- as.vector( rbind( Histo.26,Histo.45,Histo.85 )[,1] )
[1]  2  9  1 11 17 11 17 15  7

然后用轴绘图:

barplot(L, ylim = c(0,20), col=c("red","lightblue","gray"), xaxt="n")
axis(1, at = c(2,5,8), labels = c("Group1","Group2","Group3") ,tick=FALSE, cex=0.3)

我必须将at中的axis更改为c(2, 5.5, 9)才能使其正常运行。这将是输出;


                     https://i.stack.imgur.com/csckS.png

答案 1 :(得分:1)

对此有不同的解决方法,我希望使用data.tablesetDTmelt来展示新的数据集的数据框。

df1 <- cbind(Histo.85,Histo.45,Histo.26)
df1 <- data.frame(df1)

library(data.table)
setDT(df1, keep.rownames = TRUE)[]
colnames(df1) <- c("rn","85","45","26")

df2 <- melt(df1, id.vars='rn')

library(ggplot2)
ggplot(df2, aes(x=rn, y=value, fill=variable)) +
  geom_bar(stat='identity', position='dodge')

这将是情节:

bar plot