我在将百分比和计数标签放置在分组的条形图上时遇到麻烦。标签当前堆叠在一起(see link for image)。我认为这是因为我一直在参考堆叠Barplot的示例代码。我尝试将position=position_dodge(width=1)
添加到geom_text
来堆叠标签,但是收到以下警告:
警告:忽略未知的美学:位置不知道如何为PositionDodge / Position / ggproto / gg类型的对象自动选择比例。默认为连续。错误:美学必须是有效的数据列。问题的美学:位置= position_dodge(宽度= 1)。您是否输入了数据列的名称错误或忘记添加stat()?
这是我使用泰坦尼克号数据集的代码:
data("titanic_train")
head(titanic_train, 6)
library(dplyr)
library(ggplot2)
titanic_train$Survived <- as.factor(titanic_train$Survived)
summary = titanic_train %>% group_by(Survived, Sex) %>% tally %>% mutate(pct = n/sum(n))
ggplot(summary, aes(x=Sex, y=n, fill=Survived)) + geom_bar(stat="identity", position="dodge") + geom_text(aes(label=paste0(sprintf("%1.1f", pct*100),"%\n", n)), colour="black")
非常感谢您对此问题的帮助!预先谢谢你。
您可以只将position = position_dodge(width = 1)
添加到您的geom_text
呼叫中,但不在aes
之外。您的错误是由于尝试将position...
放入aes
引起的。
library(dplyr)
library(ggplot2)
library(titanic)
ggplot(summary, aes(x = Sex, y = n, fill = Survived)) +
geom_bar(stat = "identity", position = "dodge") +
geom_text(aes(label = paste0(sprintf("%1.1f", pct * 100), "%\n", n)),
colour = "black",
position = position_dodge(width = 1)) +
coord_cartesian(ylim = c(0, 550))