geom_text 位于堆积条形图中间

Jan*_*IDK 3 r ggplot2 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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在此输入图像描述

但我希望这个堆积条形图中的数字如下: 在此输入图像描述

我怎样才能改变我的 vjust 使数字位于堆积条的中间

Qui*_*ten 5

首先使用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
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述