R ggplot几何图形栏:堆栈和中心

R ggplot几何图形栏:堆栈和中心,r,ggplot2,bar-chart,R,Ggplot2,Bar Chart,我有一个数据框,以百分比为单位,列代表不同的项目,行代表不同类别受访者的相应份额。我想制作一个堆叠条形图 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)<-

我有一个数据框,以百分比为单位,列代表不同的项目,行代表不同类别受访者的相应份额。我想制作一个堆叠条形图

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")
库(ggplot2)
图书馆(E2)

test最好使用类别名称作为分隔符,而不是行名称:

test$category <- factor(c(3,4,2,1), labels=c("very i.","i.","less i.","not i."))
回答您的问题:

  • 如果某些值高于零,而其他值低于零,则堆叠条形图无法正常工作。因此,将创建两个单独的条形图(一个为负值,一个为正值)
  • 新列
    category
    用于
    fill
    参数,以将每个类别映射到不同的颜色
  • 完整代码:

    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")
    

    另一个专门为此设计的工具是HH包中的
    likert()
    。此sweet函数绘制适用于Likert、语义差异和评级量表数据的发散堆积条形图

    library(HH)
    # note use of t(test)[,4:1] to transpose and mirror dataframe for easy plotting
    # test dataframe is otherwise unaltered from OP's question
    
    likert(t(test)[,4:1], horizontal = FALSE,
           main = NULL, # or give "title",
           xlab = "Percent", # becomes ylab due to horizontal arg
           auto.key = list(space = "right", columns = 1,
                         reverse = TRUE))
    

    likert()
    的一个特别吸引人的特性是能够使用ReferenceZero参数将中性响应居中。(注意它是如何使用适当的灰色作为参考响应的):


    (这些例子通常使用竖条,但
    horizontal=TRUE
    通常更好,尤其是如果你想包括问题或刻度名称的话。)

    @sven hohenstein我似乎无法让这一点对我起作用。请看哪一个将+ve/-ve y类别弄混了!知道为什么吗?@geotheory你应该反转颜色值的向量(
    scale\u fill\u手册(values=rev(colorRampPalette(c('red','grey','green'))(4))
    )。我不确定我的还是混在一起,只是反转了颜色方案:@geotheory你想改变因子级别的顺序吗<代码>级别(d$评级)
    library(HH)
    # note use of t(test)[,4:1] to transpose and mirror dataframe for easy plotting
    # test dataframe is otherwise unaltered from OP's question
    
    likert(t(test)[,4:1], horizontal = FALSE,
           main = NULL, # or give "title",
           xlab = "Percent", # becomes ylab due to horizontal arg
           auto.key = list(space = "right", columns = 1,
                         reverse = TRUE))
    
    likert(t(test)[,4:1], horizontal=FALSE,
           main = NULL, # or give "title",
           xlab = "Percent", # becomes ylab due to horizontal arg
           ReferenceZero = 3,
           auto.key=list(space = "right", columns = 1,
                         reverse = TRUE))