[英]Filter geom_text value labels in a stacked bar chart
我想创建一个带有ggplot的堆积条形图,并为其添加(居中)标签:当值太低时,我不想显示标签。
df<-data.frame(x=unlist(strsplit("AAAABBBB","")),
z=unlist(strsplit("ABCDABCD","")),
y=c(40,5,30,10,50,60,5, 40))
# this works fine
library(ggplot2)
ggplot(df, aes(x=x, y=y, fill = z)) + geom_bar(stat="identity") +
geom_text(data = df, aes(x=x, y=y, label = y), position = position_stack(vjust=0.5))
但是当我过滤这样的值(见下文)时,它也会改变每个标签的定位。 这适用于散点图,但由于定位基于堆叠值,因此标签显示得太低。
#don't show values 5 or less
ggplot(df, aes(x=x, y=y, fill = z)) + geom_bar(stat="identity") +
geom_text(data = df[df$y > 5,], aes(x=x, y=y, label = y), position =
position_stack(vjust=0.5))
我们可以创建一个值'y1',其值小于或等于5为空( ""
)并在label
参数中使用它
df %>%
mutate(y1 = replace(y, y<=5, ""))
p2 <- ggplot(df, aes(x=x, y=y, fill = z)) +
geom_bar(stat="identity") +
geom_text(data = df, aes(x=x, y=y, label = y1),
position = position_stack(vjust=0.5))
p2
通过与OP的帖子中的第一个图比较来检查位置
p1 <- ggplot(df, aes(x=x, y=y, fill = z)) +
geom_bar(stat="identity") +
geom_text(data = df, aes(x=x, y=y, label = y),
position = position_stack(vjust=0.5))
library(ggpubr)
ggarrange(p1, p2, ncol =2, nrow = 1, labels = c("p1", "p2"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.