分组堆叠条形图:关于堆叠顺序、图形水平方向和组标签的问题

Grouped stacked bar graph: issues regarding order of stack, horizontal orientation of graph and label of groups

我遵循了这个问题的答案:

创建上图:

使用以下代码:

test  <- data.frame(person=c("8.3. The number of people coming to me \n me, who
                             are who want pizza are too many \n,
                             and too aggressive.", "group 2", "group 3", "5", "6"), 
                    value1=c(100,150,120,100,100),  # Agree   
                    value2=c(25,30,45,100,100) ,    # Neutral
                    value3=c(25,30,45,100,100),     # Disagree
                    value4=c(100,120,150,100,100),  # Agree
                    value5=c(10,12,15,100,100),     # Neutral
                    value6=c(50,40,70,100,100))     # Disagree

library(reshape2) # for melt

melted <- melt(test, "person")

melted$cat <- ''
melted[melted$variable == 'value1' | melted$variable == 'value2' | melted$variable == 'value3',]$cat <- "GP"
melted[melted$variable == 'value4' | melted$variable == 'value5'| melted$variable == 'value6',]$cat <- "LW"
melted$gender <- ''
melted[melted$variable %in% sprintf("value%i",c(1,4)),]$gender <- "Agree"
melted[melted$variable %in% sprintf("value%i",c(2,5)),]$gender <- "Disagree"
melted[melted$variable %in% sprintf("value%i",c(3,6)),]$gender <- "Neutral"



p = ggplot(melted, aes(x = cat, y = value, fill = gender)) 

p + geom_bar(stat = 'identity', position = 'stack') +   facet_grid(~ person) + 
  scale_fill_manual(values = c("orangered","green","dodgerblue2")) + 
  theme(panel.background = element_rect(fill = 'white'))

我的问题是:

如何确定堆栈的顺序,使中立介于同意和中立之间?有没有办法让图表水平,这样我就可以有更宽的 space 来解决这个问题?我还希望数字显示在每个条内,例如,最左边的红色条应该在里面写 100。

我在 R 和 Python 中使用了一些 liekert 库,但我无法对条形图进行分组,而且还有其他问题。这个 ggplot 图表是我最接近创建我需要的图表的图表,所以如果你的答案完全可以用我给出的数字重现,我将不胜感激。

要达到您想要的结果,您可以

  1. 按所需顺序设置因子水平
  2. 利用 coord_flip() 制作水平条形图,我稍微更改了 facet_grid 以将条带放在右侧并旋转条带文本标签。
  3. 通过 geom_text 添加标签,我将位置设置为 position_stack(vjust = .5) 以将标签放在条的中间


melted$gender <- factor(melted$gender, c("Agree", "Neutral","Disagree"))
p = ggplot(melted, aes(x = cat, y = value, fill = gender))
p + geom_bar(stat = 'identity', position = 'stack') +
  geom_text(aes(label = value), position = position_stack(vjust = .5)) +
  facet_grid(person~.) + 
  scale_fill_manual(values = c("orangered","green","dodgerblue2")) + 
  theme(panel.background = element_rect(fill = 'white'),
        strip.text.y = element_text(angle = 0)) +
  coord_flip()