我创建了以下图形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))
答案 0 :(得分:3)
我使用以下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()