ggplot2中geom_bar的z-index属性

4
我已经创建了以下的 ggplot 图形 enter image description here 使用以下代码:
p <- ggplot(df, aes(x=100*prop_select, y=(1500-s_meanResponse), fill=product)) + 
  geom_bar(stat='identity', width=2,  alpha=.6, color='#333333') + 
  coord_cartesian(xlim = c(0, 5)) +
  coord_flip()

print(p)

我试图有意地重叠这些条形图。我想知道如何更改每个条形图的 z-index(深度)。我尝试通过重新排序决定我的条形图的因子列的级别来实现这一点。
# Order by mean response to make sure that bars are layered correctly (does not work!)
# Switching this minus makes no difference to the bar z-index but does reverse legend entries
df <- df[sort.list(-df$s_meanResponse),] 
df$product <- factor(df$product, levels=df$product)

有人知道ggplot2是否能做到这一点吗?
编辑:
数据框的结构类似于以下:
df <- data.frame( product=c('a','b','c'), s_meanResponse=c(1120,1421,1320), prop_select=c(.3,.2,.5))

请包含一个 df 的样本。 - Matthew Plourde
你是否考虑使用带标签的散点图呢?对于条形图,你可以尝试在factor()表达式中使用levels=rev(df$product) - James Trimble
尝试重新排列级别,但没有效果。散点图是这种数据的自然选择,但我卡在了尝试这种类型的可视化上 - 客户啊? - Joe
1个回答

4
我将使用以下具有实际重叠的df:

df <- data.frame(product=c('a','b','c'), 
                 s_meanResponse=c(1120,1421,1320), 
                 prop_select=c(.311,.32,.329))

似乎无论因素水平的排序如何,绘图顺序仍然保持不变,而只是按最低到最高的y值绘制条形图。要实现自定义排序,我们需要按所需顺序逐个显式地绘制图层:
geom_bars_with_order <- function(vals)
{
  l <- list()
  for (i in vals) 
  {
    l <- c(l, geom_bar(data = df[df$product == i, ], 
                       stat='identity', width=2, alpha=.6, color='#333333'))  
  }
  l
}
# default order
ggplot(NULL, aes(x=100*prop_select, y=(1500-s_meanResponse), fill=product)) + 
  geom_bars_with_order(c("a", "b", "c")) +
  coord_cartesian(xlim = c(0, 5)) +
  coord_flip()

enter image description here

# custom order, "a" on top
ggplot(NULL, aes(x=100*prop_select, y=(1500-s_meanResponse), fill=product)) + 
  geom_bars_with_order(c("b", "c", "a")) +
  coord_cartesian(xlim = c(0, 5)) +
  coord_flip()

enter image description here


太赞了!我知道必定会有一个ggplot高手帮忙的!谢谢你,非常感激! - Joe
另外,很抱歉没有提供重叠的示例数据! - Joe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接