【问题标题】:R: Calculating percentage for Likert scale and creating barplots with those percentagesR:计算李克特量表的百分比并使用这些百分比创建条形图
【发布时间】:2018-05-25 11:08:30
【问题描述】:

我有来自男性 (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)

还有条形图:

还有来自数据的样本:

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

【问题讨论】:

  • 如果您提供数据样本以便我们进行调查会更容易。
  • 我已经上传了
  • 我无法使用您的数据集,因为我必须输入所有内容,但我会发布一些您可以使用的代码示例
  • 这只是一个变相的 dplyr 变异问题,因此是重复的,可能应该关闭。我们并不严格需要任何 ggplot 的东西。

标签: r ggplot2 dplyr bar-chart


【解决方案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

【讨论】:

  • 非常感谢!这对我帮助很大 :) 我想查看响应 /226,所以现在我有了我想要的所有百分比。但是他们有太多的小数。你知道我怎么能保持两个吗?为 0,4424525 -> 0,44。还有一件事 - 我怎样才能改变颜色?我有更多条形图和不同的颜色会很有用:) 谢谢!
  • 非常感谢!看起来比我最初的条形图更好:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 2017-03-18
  • 1970-01-01
相关资源
最近更新 更多