如何在带有ggplot的R中的多面堆叠条形图中使用不同的geom_text()标签?
我正在尝试将facet_wrap用于堆叠条形图,我希望在条形图上有标签,显示条形图每个部分的值 以钻石数据集为例: 当只有一个图形时,我的geom_文本代码可以正常工作,尽管对于较短的条形图来说比较狭窄:如何在带有ggplot的R中的多面堆叠条形图中使用不同的geom_text()标签?,r,ggplot2,facet,facet-wrap,geom-text,R,Ggplot2,Facet,Facet Wrap,Geom Text,我正在尝试将facet_wrap用于堆叠条形图,我希望在条形图上有标签,显示条形图每个部分的值 以钻石数据集为例: 当只有一个图形时,我的geom_文本代码可以正常工作,尽管对于较短的条形图来说比较狭窄: diamonds %>% ggplot(aes(x = cut, fill = clarity)) + geom_bar() + geom_text(data = . %>% group_by(cut, clarity) %>% ta
diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
geom_text(data = . %>%
group_by(cut, clarity) %>%
tally() %>%
ungroup() %>%
group_by(cut) %>%
ungroup(),
aes(y = n, label = n),
position = position_stack(0.5),
show.legend = FALSE)
但是,添加镶嵌面时,所有标签都显示在所有单个镶嵌面中:
diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
facet_wrap(~ color) +
geom_text(data = . %>%
group_by(cut, clarity) %>%
tally() %>%
ungroup() %>%
group_by(cut) %>%
ungroup(),
aes(y = n, label = n),
position = position_stack(0.5),
show.legend = FALSE)
如何使标签只显示在相关栏上
谢谢 我认为您需要将颜色包含在组_by+tally中,以便将其分配到正确的方面:
diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
facet_wrap(~ color,scale="free_y") +
geom_text(data = . %>%
count(cut, clarity,color),
aes(y = n, label = n),size=1,
position = position_stack(0.5),
show.legend = FALSE)
我个人认为
.count..
特殊变量更容易使用
diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
facet_wrap(~ color,scale="free_y") +
stat_count(geom = "text",
aes(y =..count.., label = ..count..),
position=position_stack(0.5), size = 2)
将颜色包括在组中\u by+tally非常有效,谢谢!