geom_text 在堆积条形图上的中间位置
geom_text position middle on the stacked bar chart
# Loading data
data(CPS85, package = "mosaicData")
# Count the number of females and males in each sector
plotdata <- group_by(CPS85,sector) %>%
count(sex)
# Print the data
print(plotdata)
# Construct a ggplot object according requirement above and assign it to 'plt'
plt <- ggplot(plotdata,
aes(x = sector,
y = n))+
geom_col(aes(fill=sex))+
geom_text(aes(label=n),
position = position_stack(vjust = 0.5))+
labs(x = "",
y = "Number of persons",
title = "")
# Display the stacked bar chart
plt
但我希望此堆叠条形图中的数字如下所示:
我如何更改我的 vjust 以使数字位于堆叠条的中间
首先使用geom_bar
并设置stat = "identity"
。之后使用 position = position_stack(vjust = 0.5)
。您可以使用以下代码:
# Construct a ggplot object according requirement above and assign it to 'plt'
plt <- ggplot(plotdata,aes(x = sector, y = n, fill = sex))+
geom_bar(stat="identity")+
geom_text(aes(label=n), position = position_stack(vjust = 0.5))+
labs(x = "",
y = "Number of persons",
title = "")
# Display the stacked bar chart
plt
输出:
# Loading data
data(CPS85, package = "mosaicData")
# Count the number of females and males in each sector
plotdata <- group_by(CPS85,sector) %>%
count(sex)
# Print the data
print(plotdata)
# Construct a ggplot object according requirement above and assign it to 'plt'
plt <- ggplot(plotdata,
aes(x = sector,
y = n))+
geom_col(aes(fill=sex))+
geom_text(aes(label=n),
position = position_stack(vjust = 0.5))+
labs(x = "",
y = "Number of persons",
title = "")
# Display the stacked bar chart
plt
但我希望此堆叠条形图中的数字如下所示:
我如何更改我的 vjust 以使数字位于堆叠条的中间
首先使用geom_bar
并设置stat = "identity"
。之后使用 position = position_stack(vjust = 0.5)
。您可以使用以下代码:
# Construct a ggplot object according requirement above and assign it to 'plt'
plt <- ggplot(plotdata,aes(x = sector, y = n, fill = sex))+
geom_bar(stat="identity")+
geom_text(aes(label=n), position = position_stack(vjust = 0.5))+
labs(x = "",
y = "Number of persons",
title = "")
# Display the stacked bar chart
plt
输出: