R ggplot2中比例堆叠条形图的绝对标签
我试图创建一个具有比例值(百分比)的堆叠条形图,但同时在各个条形图的顶部显示绝对值。目前,我只能在图表上错误的位置显示值 我的R ggplot2中比例堆叠条形图的绝对标签,r,ggplot2,R,Ggplot2,我试图创建一个具有比例值(百分比)的堆叠条形图,但同时在各个条形图的顶部显示绝对值。目前,我只能在图表上错误的位置显示值 我的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
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])
#按数字对字符排序并打印
p1在应用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])
库(ggplot2)
检查可能的解决方案。太棒了!非常感谢你的帮助!
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])