带子类别的GGplot2

时间:2015-12-08 15:39:56

标签: r plot ggplot2

我正在尝试使用错误栏构建直方图。与this类似的东西。

但我的数据有多个类别和子类别。每个子类别都有2个需要绘制的值。我想出了一个绘制误差线的方法。但我错过的是如何绘制两个条形图。

#!/usr/bin/Rscript

library(ggplot2)
library(grid)

## create some data with asymmetric fill aes to generalize solution 
data <- read.table(text = "Group Category Value Value2
                   AD-0 CF 15  10
                   AR-0 CF 12  10
                   C S3   87    1", 
                   header=TRUE)

# user-level interface 
axis.groups = function(groups) {
  structure(
    list(groups=groups),
    ## inheritance since it should be a element_text
    class = c("element_custom","element_blank")  
  )
}
# returns a gTree with two children: 
# the categories axis
# the groups axis
element_grob.element_custom <- function(element, x,...)  {
  cat <- list(...)[[1]]
  groups <- element$group
  ll <- by(data$Group,data$Category,I)
  tt <- as.numeric(x)

  grbs <- Map(function(z,t){
    labs <- ll[[z]]
    vp = viewport(
             x = unit(t,'native'), 
             height=unit(2,'line'),
             width=unit(diff(tt)[1],'native'),
             xscale=c(0,length(labs)))
    grid.rect(vp=vp)
    textGrob(labs,x= unit(seq_along(labs)-0.5,
                                'native'),
             y=unit(2,'line'),
             vp=vp)
  },cat,tt)

  g.X <- textGrob(cat, x=x)
  gTree(children=gList(do.call(gList,grbs),g.X), cl = "custom_axis")
}

## # gTrees don't know their size 
grobHeight.custom_axis = 
  heightDetails.custom_axis = function(x, ...)
  unit(3, "lines")

## the final plot call
ggplot(data=data, aes(x=Category, y=Value2, fill=Group)) + 
  geom_bar(position = position_dodge(width=0.9),stat='identity') +
  geom_text(aes(label=paste(Value2, "%")),
            position=position_dodge(width=0.9), vjust=-0.25)+
  theme(axis.text.x = axis.groups(unique(data$Group)),
        legend.position="none")

执行两次最终绘图调用将无法完成工作,因为您正在重写数据。我想知道是否有办法在R中做到这一点。

我是R的新手。我知道在python中你可以使用相同的轴并计算当前柱的距离来绘制它。

rects1 = ax.bar(ind, AE1, width,
            color='0.2',
            error_kw=dict(elinewidth=2,ecolor='red'),
            label='Pow')

rects2 = ax.bar(ind+width, AE2, width,
                color='0.5',
                error_kw=dict(elinewidth=2,ecolor='black'),
                label='Perf')

R中有类似内容吗?

1 个答案:

答案 0 :(得分:0)

这可以帮到你

首先需要从宽转换为

library(reshape2)
data_long <- melt(data, id.vars=c("Group", "Category"))

然后绘制

ggplot(data=data_long, aes(x=Group, y=value, fill=variable)) + 
  geom_bar(position = "dodge",stat='identity')

这就是你想要的吗?