具有多个虚拟变量的饼图

问题描述 投票:0回答:1

假设有4个人和3个组(A,B,C),并且1表示它属于X组,在其他情况下,它属于0组。假设我们有一个这样的数据库:

# A  B  C
1 0  0  1
2 0  1  0
3 1  0  0
4 1  0  0

我想做的是一个包含每个组的饼图。

我正在尝试的代码

ggplot(data, aes(x="", y=data$A)) +
  geom_bar(stat="identity", width=1) +
  coord_polar("y", start=0)

但是,它仅绘制一个变量的饼图。谢谢

r plot new-operator pie-chart
1个回答
0
投票

我认为这段代码可以执行您想要的绘图。在绘制情节之前,我使用pivot_longer进行了一些编码。

library(tidyverse)
df %>%
  pivot_longer(cols = c(A,B,C),
               names_to = "group",
               values_to = "people") %>%
  group_by(group) %>%
  summarize(Sumppl = sum(people)) %>%
  ggplot(aes(x="", y = Sumppl, fill = group)) +
  geom_bar(stat = "identity",width = 1, position = "stack")+
  coord_polar("y") + 
  theme_minimal()+
  theme(axis.text.x=element_blank())

Pie plot

© www.soinside.com 2019 - 2024. All rights reserved.