ggplot geom_bar:堆栈和中心 [英] ggplot geom_bar: stack and center

查看:134
本文介绍了ggplot geom_bar:堆栈和中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以百分比表示股份的数据框,代表不同项目的受访者各自的份额。

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

好吧,但我希望以
a为中心):正面答案(非常我和我)和底部两个类别(更少i而不是i)下来。

b)每个类别(非常我,我,少我,不是我)具有相同的颜色。

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.

推荐答案

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

这篇关于ggplot geom_bar:堆栈和中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆