我正在尝试使用条形图中的geom_bar
每个类别的值来绘制堆叠的条形图,并对其进行标记。由于某些类别的值较小,因此条形图的相应段的高度有时很小。所以,我正在尝试使用geom_text
.
我试图定义一个向量,称为size
,它根据我试图绘制的变量的值而变化,但是,尽管标签的大小在类别之间确实有所不同,但它似乎与值无关。另外,我不确定为什么我会在图表的右侧获得标签大小的图例。
这是我正在使用的代码的剥离版本:
library(ggplot2)
library(plyr)
library(scales)
Var1 = as.factor(rep(c("A", "B", "C", "D", "E", "F"),2))
Var2 = as.factor(rep(c("Y1","Y2"),each=6))
Freq = c(0.4, 0.1, 0.3, 0.1, 0.05, 0.05,0.2,0.2,0.3,0.2,0.05,0.05)
Data = data.frame(Var1, Var2, Freq)
Data <- ddply(Data, .(Var2), mutate, y = cumsum(Freq)-Freq/2)
size = ifelse(Data$Freq > 0.05, 10, 3)
label = paste(round(Data$Freq*100,0),"%", sep = "")
p = ggplot(data = Data, aes(x = factor(''), y = Freq, fill = Var1)) +
geom_bar(stat = "identity",position = "fill", width = 1) +
scale_fill_brewer(palette = 3) +
facet_grid(facets = . ~ Var2) +
geom_text(aes(y = y, label = label,
position ="identity", face = "bold"), size = size, hjust=0.5, vjust=0.5) +
xlab('') + ylab('') + labs(fill = '') + ggtitle('Example') +
theme(axis.text.y = element_text(size=14,face="bold"),
panel.background = element_blank(),
plot.title = element_text(size = 20, colour = "black", face = "bold"))
p
据我所知,这个问题是由方面引起的,因为这个稍微简化的版本(即没有方面)工作正常:
library(ggplot2)
library(plyr)
library(scales)
Var1 = as.factor(c("A", "B", "C", "D", "E", "F"))
Freq = c(0.4, 0.1, 0.3, 0.1, 0.05, 0.05)
y = cumsum(Freq)-Freq/2
Data = data.frame(Var1, Freq, y)
size = ifelse(Data$Freq > 0.05, 10, 3)
label = paste(round(Data$Freq*100,0),"%", sep = "")
p = ggplot(data = Data, aes(x = factor(''), y = Freq, fill = Var1)) +
geom_bar(stat = "identity",position = "fill", width = 1) +
scale_fill_brewer(palette = 3) +
geom_text(aes(y = y, label = label,
position ="identity", face = "bold"), size = size, hjust=0.5, vjust=0.5) +
xlab('') + ylab('') + labs(fill = '') + ggtitle('Example') +
theme(axis.text.y = element_text(size=14,face="bold"),
panel.background = element_blank(),
plot.title = element_text(size = 20, colour = "black", face = "bold"))
p