我正在尝试在 ggplot 2 中创建带有值标签的计数值并排条形图,但我似乎无法弄清楚如何向各个并排条形图添加值标签。
我正在使用以下数据集:https://www.kaggle.com/datasets/shubhamgupta012/titanic-dataset/data
这是我使用的代码:
titanic <- read_csv("titanic.csv")
titanicgg <- ggplot(titanic)
titanicgg + geom_bar(aes(x=Pclass, fill=as.factor(Survived)), position=position_dodge2(preserve = "single")) +
labs(title="Survival by Passenger Class", x = "Passenger Class", y = "Count") +
theme_classic() + theme(plot.title = element_text(hjust = .5)) +
scale_fill_manual(values = c("red3", "steelblue3"), name=element_blank(),
labels=c("Did Not Survive", "Survived")) +
theme(plot.title=element_text(size=25, face="bold"), axis.title=element_text(size=15),
legend.text = element_text(size = 13)) +
geom_text(stat = 'count',aes(label = ..count.., vjust = -0.2, x=Pclass), position = position_dodge(.9))
我希望获得一个带有各个并排条形图的值标签的图,但值标签却显示为每个类类别的总数,如下图所示。我怎样才能让标签出现在各个酒吧(头等舱幸存、头等舱未幸存等的各个标签)?
geom_text
函数应在Survived
中包含
aes()
变量
library(ggplot2)
ggplot(titanic, aes(x = Pclass, fill = as.factor(Survived))) +
geom_bar(position = position_dodge2(preserve = "single")) +
labs(title = "Survival by Passenger Class", x = "Passenger Class", y = "Count") +
theme_classic() +
theme(plot.title = element_text(hjust = .5)) +
scale_fill_manual(values = c("red3", "steelblue3"),
name = element_blank(),
labels = c("Did Not Survive", "Survived")) +
theme(plot.title = element_text(size = 25, face = "bold"),
axis.title = element_text(size = 15),
legend.text = element_text(size = 13)) +
geom_text(stat = 'count',
aes(label = ..count.., group = Survived,
vjust = -0.2, x = Pclass),
position = position_dodge(width = 0.9))