gpt4 book ai didi

r - ggplot stacked bar - 隐藏标签但保留标签定位

转载 作者:行者123 更新时间:2023-12-02 17:06:09 29 4
gpt4 key购买 nike

我在 ggplot 中有一个堆积条形图,geom_text() 标签以每个条为中心。我想隐藏小条上的标签,这样图表就不会显得过于拥挤。我可以使用下面的代码来做到这一点,但它会弄乱标签的位置,正如您在下面的链接图片中看到的那样(它们不再居中)。

有没有一种方法可以隐藏条形图标签而不会弄乱其余标签的位置?

ggplot(data=outcome,
aes(x = category, y=percent,fill = outcome)) +
geom_bar(stat='identity') +
coord_flip() +
geom_text(data=outcome %>% filter(percent>=0.1),aes(label = percent), size = 3,position = position_stack(vjust = 0.5),
check_overlap=TRUE)

stacked bar chart with mispositioned labels

最佳答案

您可以使用 ifelse() 语句。每当我不想要标签时,我都会在这里放空白,但 NA 也可以。

library(ggplot2)

df = data.frame(
x = factor(c(1, 1, 2, 2)),
y = c(1, 3, 2, 1),
grp = c("a", "b", "a", "b")
)

ggplot(data = df, aes(x, y, fill = grp)) +
geom_col() +
coord_flip() +
geom_text(aes(label = ifelse(y > 1, y, "")),
position = position_stack(vjust = 0.5),
size = 3)

reprex package 创建于 2018-08-07 (v0.2.0).

关于r - ggplot stacked bar - 隐藏标签但保留标签定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51734822/

29 4 0