R:计算李克特量表的百分比并创建具有这些百分比的柱状图

时间:2018-05-25 11:08:30

标签: r ggplot2 dplyr bar-chart

我有来自男性(1)和女性(2)的数据以及对李克特量表的回答。我试图计算每一个人的百分比(例如男性,在所有226个受访者中有1个回答)。因此,百分比需要代表所有226个百分比,以便我可以看到每个受访者的百分比。

条形图非常漂亮,但我无法将y比例转换为百分比(目前设置为值)。

这是我的意见:

barplot(table(Short$Gen,Short$optq18), beside=T, cex.names=0.7, 
        legend.text=c("Male", "Female"), args.legend=list(x=3.5,y=60,cex=0.8),
        col=c("bisque1", "cyan4"),
        xlab = "It is important to control monthly expenses",
        ylab = "Percentage",
        )
text(1.4,5, "0,44%", cex=0.6)
text(2.4,4, "0%", cex=0.6)
text(4.6,8.5, "2,21%", cex=0.6)
text(5.6,7, "1,76%", cex=0.6)
text(7.5,18, "6,63%", cex=0.6)
text(8.5,26.5, "10,17%", cex=0.6)
text(10.6,37, "15%", cex=0.6)
text(11.6,47.5, "19,4%", cex=0.6)
text(13.5,41, "16,8%", cex=0.6)
text(14.6,63, "17,43%", cex=0.6)

条形图:

enter image description here

来自数据的样本:

enter image description here

其中Country有3个级别,Gender有2个,optq有5个(1,2,3,4,5)Likert量表

1 个答案:

答案 0 :(得分:1)

# example data
dt = data.frame(Gen = c(1,1,1,1,1,2,2,2,2,2),
                optq18 = c(1,2,2,2,3,2,1,1,1,3))

library(tidyverse)

dt %>%
  group_by(optq18) %>%                                            # for each question number
  count(Gen) %>%                                                  # count gender type
  mutate(Prc = round(n/sum(n),2),                                 # get percentage of gender up to 2 decimal points
         Gen = ifelse(Gen == 1, "Male", "Female")) %>%            # update variable
  ungroup() %>%                                                   # forget the grouping
  mutate(Prc_text = paste0(Prc*100, "%")) %>%                     # update how percentages appear
  ggplot(aes(factor(optq18), Prc, fill=Gen))+                     # plot
  geom_bar(position = "dodge", stat = "identity")+                # add bars
  geom_text(aes(label=Prc_text), position = position_dodge(width=1), size=8)+  # add percentages on top of bars
  xlab("")+                                                       # no x axis title
  ylab("Percentage")+                                             # y axis title
  labs(caption = "It is important to control monthly expenses")+  # add your comment
  theme(plot.caption = element_text(hjust = 0.5))+                # put comment in the middle
  scale_fill_manual(values=c("Female"="green", "Male"="orange"))  # pick your colours

enter image description here