我希望两个不同嵌套分组变量的级别出现在绘图下方的单独行上,而不是出现在图例中.我现在掌握的是以下代码:

data <- read.table(text = "Group Category Value
    S1 A   73
    S2 A   57
    S1 B   7
    S2 B   23
    S1 C   51
    S2 C   87", header = TRUE)

ggplot(data = data, aes(x = Category, y = Value, fill = Group)) + 
  geom_bar(position = 'dodge') +
  geom_text(aes(label = paste(Value, "%")), 
            position = position_dodge(width = 0.9), vjust = -0.25)

在此处输入图像描述

我想要的是这样的:

在此处输入图像描述

有什么 idea 吗?

推荐答案

可以为axis.text.x创建自定义元素函数.

在此处输入图像描述

library(ggplot2)
library(grid)

## create some data with asymmetric fill aes to generalize solution 
data <- read.table(text = "Group Category Value
                   S1 A   73
                   S2 A   57
                   S3 A   57
                   S4 A   57
                   S1 B   7
                   S2 B   23
                   S3 B   57
                   S1 C   51
                   S2 C   57
                   S3 C   87", 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=Value, fill=Group)) + 
  geom_bar(position = position_dodge(width=0.9),stat='identity') +
  geom_text(aes(label=paste(Value, "%")),
            position=position_dodge(width=0.9), vjust=-0.25)+
  theme(axis.text.x = axis.groups(unique(data$Group)),
        legend.position="none")

R相关问答推荐

通过R访问MoveApps API

如果窗口在CLARME或集团之外,则有条件领先/滞后滚动总和返回NA

如何在R中正确对齐放射状图中的文本

寻找图片边缘

如何计算前一行的值,直到达到标准?

如何写一个R函数来旋转最后n分钟?

如何通过Docker部署我的shiny 应用程序(多个文件)

如何在编辑列时更新可编辑数据表,并使用该表在Shiny中执行连续计算

在GGPLATE中将突出的点放在前面

如何在ggplot图中找到第二轴的比例

如何在观测缺失的地方添加零

通过在colname中查找其相应值来创建列

使用data.table::fcase()而不是dplyr::case_When()时保持值

如何通过匹配R中所有可能的组合来从宽到长旋转多个列?

如何在ggplot2中绘制具有特定 colored颜色 的连续色轮

R -在先前group_by级别汇总时获取最大大小子组的计数

根据纬度和距离连接两个数据集

如何平滑或忽略R中变量的微小变化?

在gggraph中显示来自不同数据帧的单个值

如何将这个小列表转换为数据帧?