Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

r - ggplot geom_bar: stack and center

I have a dataframe with shares in percent,columns representing different items, rows the respective share of interviewees answering in different categories. I want to produce a stacked barchart.

library(ggplot2)
library(reshape2)
 test<-data.frame(i1=c(16,40,26,18),
               i2=c(17,46,27,10),
               i3=c(23,43,24,10),
               i4=c(19,25,20,36))
 rownames(test)<-c("very i.","i.","less i.","not i.")

test.m<-melt(test)

ggplot(test.m, aes(x=variable, y=value, fill=value)) + 
   geom_bar(position="stack", stat="identity")

Looks o.k., but I want
a) center the bars: positive answers (very i. and i) up and the bottom two classes (less i. and not i.) down.
b) each category (very i, i, less i, not i,) having the same colour.

Any help would be much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is better to use the category names as a separator instead of row names:

test$category <- factor(c(3,4,2,1), labels=c("very i.","i.","less i.","not 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. 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")

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...