R语言 如何用ggplot2创建100%堆积条形图?

kmbjn2e3  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(132)

我试过在rstudio中创建一个100%的堆叠条形图,但是还没有找到一种有效的方法(也试过使用“位置”,但是r不知何故没有识别出这一点)
现在,我的代码如下所示:

ggplot(andmed, aes(x= eesmärk, group = Class)) + 
  geom_bar(aes(fill = factor(Class))) + 
  scale_fill_brewer(type = "div", palette = 2) + 
  labs(x = "eesmärk/kaaslane", y = "protsent", fill="Klass") + 
  ggtitle("...")

(一个普通的条形图。a pic of what it looks like)希望它看起来类似于:(但这是在SAS中制作的)how i would like it to look like

cwxwcias

cwxwcias1#

正如MrFlick所说,您可以使用position = "fill"来填充整个堆叠条形图。(DSC)占据了条形图的大部分,您可能只想为特定组绘制geom_text(),就像你的示例条形图一样,我通过为所有组设置geom_text()来实现这一点,但只允许一个组(carb == 4)使用alpha可见。

library(tidyverse)
library(scales)
data(mtcars)

# calculate percentages, put into dataframe
df <- mtcars %>%
  mutate(carb = factor(carb)) %>% mutate(gear = factor(gear)) %>%
  group_by(gear, carb) %>%
  summarize(n = n()) %>%
  mutate(freq = n / sum(n)) %>%
  mutate(per = label_percent()(freq))  # from the scales package

ggplot(df, aes(x = gear, fill = carb)) +
  geom_bar(position = "fill") +
  geom_text(aes(label = per), 
            stat = "count",
            alpha = ifelse(df$carb == "4", 1, 0), # conditional transparency for geom_text
            position = position_fill(vjust = 0.5))

相关问题