英文:
Create a pie chart of multiple columns
问题
我想创建一个包含多列数据的饼图。这种略显不同寻常的组合是为了评估一项大型调查的结果。答案一直是是/否,而且有多列数据重叠,因此简单地合并它们会改变陈述。最终,需要每列数据中的“是”答案的绝对数量。
#示例表格:
x <- read.csv2(file = textConnection("a;b;c;d
yes;no;yes;no
no;no;yes;no
no;no;yes;no
no;yes;no;no
no;yes;no;no
no;no;no;yes
no;no;no;yes
no;no;yes;yes
no;no;yes;yes
no;yes;yes;no
yes;yes;no;no
yes;yes;no;no
yes;yes;no;no
yes;yes;yes;no
yes;no;yes;no
yes;no;yes;yes
yes;no;yes;yes
no;no;no;yes
no;no;no;no
no;no;no;no
no;no;yes;no
no;no;yes;no
yes;no;no;no
yes;no;no;no"))
最终,应该有一个饼图,以百分比显示a列中的“是”答案的数量(x%),b列中的“是”答案的数量(y%)...以此类推。
感谢您提前的帮助。
英文:
I want to create a pie chart of multiple columns. This somewhat unusual constellation is necessary for the evaluation of a large survey. The answers were always yes/no, with several columns overlapping with yes/no, so simply merging them would change the statement. In the end, an absolute number of yes answers would be needed per associated column in total.
#example table:
x <- read.csv2(file = textConnection("a;b;c;d
yes;no;yes;no
no;no;yes;no
no;no;yes;no
no;yes;no;no
no;yes;no;no
no;no;no;yes
no;no;no;yes
no;no;yes;yes
no;no;yes;yes
no;yes;yes;no
yes;yes;no;no
yes;yes;no;no
yes;yes;no;no
yes;yes;yes;no
yes;no;yes;no
yes;no;yes;yes
yes;no;yes;yes
no;no;no;yes
no;no;no;no
no;no;no;no
no;no;yes;no
no;no;yes;no
yes;no;no;no
yes;no;no;no"))
In the end, there should be a pie chart showing in percent the a's amount of yes (x%), b's amount of yes (y%)... and so on.
Thanks in advance for your help.
答案1
得分: 1
这显示了每列的“yes”绝对数量。
library(dplyr)
library(tidyr)
library(ggplot2)
x %>%
pivot_longer(cols = everything()) %>%
summarise(res = sum(value == "yes"), .by = name) %>%
ggplot(aes(x="", y=res, fill=name)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +
geom_text(aes(label = res), position = position_stack(vjust = 0.5),
color = "white", size=6) +
scale_fill_brewer(palette="Set1") +
theme_void()
英文:
This shows the absolute number of "yes" for each column.
library(dplyr)
library(tidyr)
library(ggplot2)
x %>%
pivot_longer(cols = everything()) %>%
summarise(res = sum(value == "yes"), .by = name) %>%
ggplot(aes(x="", y=res, fill=name)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +
geom_text(aes(label = res), position = position_stack(vjust = 0.5),
color = "white", size=6) +
scale_fill_brewer(palette="Set1") +
theme_void()
答案2
得分: 1
Reshape from wide-to-long, keep only "yes" rows, then get counts and plot:
d <- stack(x)
tbl <- table(d[d$values == "yes", "ind"])
pie(tbl, labels = paste(names(tbl), "-", round(prop.table(tbl) * 100), "%"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论