R中有两个类别的堆叠的小号

发布于 2025-02-07 22:06:49 字数 747 浏览 2 评论 0原文

我正在尝试在R中创建一个堆叠的Barplot,以可视化两组的差异。

我的数据集看起来像这样:

用户我希望user
ABC男性
DEF女性
ghi女性
XYZ女性
JKL男性
ABC男性
XYZ男性XYZ
XYZ女性,

在X轴上,计数或百分比<< Y轴上的代码> a ,a的类别是堆栈,填充或不同的组。

编辑:

ggplot(data, aes(x=User, fill = A)) + 
  geom_bar(position = "fill") + 
  scale_fill_brewer(palette = "BrBG") + 
  labs(y = "Percent") 

有没有办法显示堆栈上的百分位标签?

I am trying to create a stacked barplot in R to visualize differences in two groups.

My dataset looks like this:

AUser
ABCMale
DEFFemale
GHIFemale
XYZFemale
JKLMale
ABCMale
XYZMale
XYZFemale

I would like the User to be on the x-axis, the count or percentage of A on the y-axis, and the categories of A to be the stacks or the fill or the different groups.

Edit:

ggplot(data, aes(x=User, fill = A)) + 
  geom_bar(position = "fill") + 
  scale_fill_brewer(palette = "BrBG") + 
  labs(y = "Percent") 

Is there a way to show the percent labels on the stacks?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冰魂雪魄 2025-02-14 22:06:49

您可以先计算百分比,然后使用这些值在geom_text中添加为标签。

library(tidyverse)

df %>%
  count(User, A) %>%
  group_by(User) %>%
  mutate(pct = n / sum(n)) %>%
  ggplot(aes(x = User, y = pct, fill = A)) +
  geom_col(width = 0.7) +
  geom_text(aes(label = paste0(round(pct * 100), '%')),
            position = position_stack(vjust = 0.5)) +
  scale_fill_brewer(palette = "BrBG") + 
  labs(y = "Percent")

输出

df <- structure(list(A = c("ABC", "DEF", "GHI", "XYZ", "JKL", "ABC", 
"XYZ", "XYZ"), User = c("Male", "Female", "Female", "Female", 
"Male", "Male", "Male", "Female")), class = "data.frame", row.names = c(NA, 
-8L))

You can calculate percentage first, then use those values to add as labels in geom_text.

library(tidyverse)

df %>%
  count(User, A) %>%
  group_by(User) %>%
  mutate(pct = n / sum(n)) %>%
  ggplot(aes(x = User, y = pct, fill = A)) +
  geom_col(width = 0.7) +
  geom_text(aes(label = paste0(round(pct * 100), '%')),
            position = position_stack(vjust = 0.5)) +
  scale_fill_brewer(palette = "BrBG") + 
  labs(y = "Percent")

Output

enter image description here

Data

df <- structure(list(A = c("ABC", "DEF", "GHI", "XYZ", "JKL", "ABC", 
"XYZ", "XYZ"), User = c("Male", "Female", "Female", "Female", 
"Male", "Male", "Male", "Female")), class = "data.frame", row.names = c(NA, 
-8L))
我纯我任性 2025-02-14 22:06:49

您可以尝试

library(ggplot2)
library(dplyr)
df %>%
  group_by(User) %>%
  count(A) %>%
  ggplot(aes(x = User, y = n, fill = A)) +
  geom_col()

“在此处输入图像描述”

You may try

library(ggplot2)
library(dplyr)
df %>%
  group_by(User) %>%
  count(A) %>%
  ggplot(aes(x = User, y = n, fill = A)) +
  geom_col()

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文