1

我正在尝试创建一个堆积条形图,它具有比例值(百分比),但同时在各个条形图的顶部显示绝对值。目前,我只能在图表的错误位置显示值。

data.frame看起来像这样:

   Var1 Freq pltype Num
1    SA   18     A1   2
2    SN    2     A1   4
3    UA   18     A1   1
4    SA    4     A2   2
5    UA   34     A2   1
6    SA    8     A3   2
7    SN    1     A3   4
8    UA   29     A3   1
9    SA   21     A4   2
10   SN   10     A4   4
11   UA    7     A4   1
12    N    2     A5   3
13   SA   14     A5   2
14   SN    1     A5   4
15   UA   21     A5   1
16   SA   11     A6   2
17   SN    1     A6   4
18   UA   26     A6   1
19   SA    3     A7   2
20   SN   16     A7   4
21   UN   19     A7   5
22    N    6     A8   3
23   SA    5     A8   2
24   UA   27     A8   1

到目前为止,我已经创建了这段代码:

    #Ordered characters by numbers and plotted them
    p1 <- ggplot(f[order(f$Num), ],aes(x=pltype,y=(Freq*100)/sum(data.frame(df[[exp]][1])$Freq),fill=Num))+
      geom_bar(stat="identity")
    p1+scale_fill_brewer(palette="Pastel1",labels=tp_code)+
      theme(axis.text.x = element_text(angle = 30, hjust = 1, vjust=1)) + 
      xlab("Question")+ylab("Percentage")+geom_text(aes(label=Freq))+
      ggtitle(names(df)[exp])

这给了我以下堆积条形图:

测试

我使用“R Graphics Cookbook”中的代码首先创建了频率的累积总和:

ce <- arrange(f, pltype, desc(Freq))
ce <- ddply(ce, "pltype",transform, label_y = cumsum(Freq))

geom_text通过弄乱我无法使代码正常工作来尝试不同的排列。此代码还存在一个问题,即它显示的是累积总和,而不是每个类别中的绝对值。

任何帮助将不胜感激!

4

1 回答 1

3

在应用 ggplot 代码之前,我会创建您的累积总和和百分比:

library(ggplot2)

f <- read.table("I:/ggplot.txt",header=T)
f <- f[order(f$Num),]
f$Num <- as.factor(f$Num)
tp_code <-unique(f$Var1[order(f$Num)])
for(i in 1:length(unique(f$pltype))){
f$Pct[f$pltype==unique(f$pltype)[i]] <- f$Freq[f$pltype==unique(f$pltype)[i]]*100/sum(f$Freq[f$pltype==unique(f$pltype)[i]])
f$cumPct[f$pltype==unique(f$pltype)[i]] <- cumsum(f$Pct[f$pltype==unique(f$pltype)[i]])
}

    #Ordered characters by numbers and plotted them
    p1 <- ggplot(f,aes(x=pltype,y=Pct,fill=Num))+
      geom_bar(stat="identity")
    p1+scale_fill_brewer(palette="Pastel1",label=tp_code)+
      theme(axis.text.x = element_text(angle = 30, hjust = 1, vjust=1)) + 
      xlab("Question")+ylab("Percentage")+geom_text(aes(x=pltype,y=cumPct,label=Freq,vjust=1))+
      ggtitle(names(df)[exp])

另外,我添加了vjust=1将标签放在每个栏顶部的正下方。您可以使用它并根据需要对其进行格式化。这会产生以下结果:在此处输入图像描述

于 2013-09-10T16:52:09.790 回答