【问题标题】:bar z-index for ggplot2 geom_barggplot2 geom_bar 的条形 z-index
【发布时间】:2014-07-29 13:42:47
【问题描述】:

我已经创建了以下图形 ggplot

使用以下代码;

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的样本。
  • 您会考虑使用带有标记点的散点来代替吗?对于条形图,您可以查看 levels=rev(df$product) 是否适用于 factor() 表达式。
  • 尝试重新排序级别无效。散点图是此类数据的自然选择,但我一直在尝试这种类型的可视化 - 客户,嗯?

标签: r ggplot2


【解决方案1】:

我正在使用以下具有实际重叠的 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()

# 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()

【讨论】:

  • 太棒了!我知道 ggplot 忍者会在某个时候来救援!谢谢 1,000,000!
  • 另外,很抱歉没有提供重叠的示例数据!