且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ggplot geom_bar:堆栈和中心

更新时间:2023-01-28 12:50:26

test$category <- factor(c(3,4,2,1), labels=c("very i.","i.","less i.","not i."))

(因素级别的排序完成(最低:不是i。,最高:非常i。)。

(The ordering of the factor levels is done with repect to the stacked barplot (lowest: not i., highest: very i.).

test.m <- melt(test)

回答您的问题:

To answer your questions:


  1. 如果某些值高于或低于其他值,则堆积的棒图效果不佳因此,会创建两个单独的barlot(一个为负值,一个为正值)。
  2. 新列 category 用于 fill 参数将每个类别映射到不同的co
  1. Stacked barplots do not work well if some values are above and others are below zero. Hence, two separate barplots are created (one with negative values, one with positive values).
  2. The new column category is used for the fill parameter to map each category to a different colour.

完整的代码:

The complete code:

ggplot(test.m, aes(x=variable, fill=category)) + 
      geom_bar(data = subset(test.m, category %in% c("less i.","not i.")),
               aes(y = -value), position="stack", stat="identity") +
      geom_bar(data = subset(test.m, !category %in% c("less i.","not i.")), 
               aes(y = value), position="stack", stat="identity")