1

当我按 R 中的因子对数据进行分组时,我似乎无法在每个条上绘制 % 标签。有什么想法吗?谢谢!

# Load libraries
library(ggplot2)        # for plotting
library(likert)         # for analyzing likert data
library(plyr)           # for using plot.percents=TRUE

# Create dataset
q1_pre <- c("Strongly agree", "Strongly agree", "Strongly agree", "Strongly agree", "Disagree", "Neither", "NA", "Somewhat agree", "Somewhat disagree","Neither")
q2_pre <- c("Strongly agree", "Strongly agree", "Strongly agree", "Strongly agree", "Disagree", "Neither", "NA", "Somewhat agree", "Somewhat disagree","Neither")

lab_pre <- rep("pre", length(q1_pre))
pre <- cbind(lab_pre, q1_pre, q2_pre)

q1_post <- c("Strongly disagree", "Strongly disagree", "Strongly disagree", "Strongly disagree", "Strongly disagree", "Neither", "NA", "Somewhat disagree", "Somewhat agree","Neither")
q2_post <-c("Strongly disagree", "Strongly disagree", "Strongly disagree", "Strongly disagree", "Strongly disagree", "Neither", "NA", "Somewhat disagree", "Somewhat agree","Neither")
lab_post <- rep("post", length(q1_post))
post <- cbind(lab_post, q1_post, q2_post)

df <- data.frame(rbind(pre, post))
df_lev <- rev(c("Strongly agree", "Somewhat agree", "Neither", "Somewhat disagree", "Strongly disagree", "NA"))

for (i in 2:ncol(df)) {
    df[ , i] <- factor(df[, i], levels=df_lev)
}

# Convert to likert structure
df.likert <- likert(df[2:ncol(df)], grouping=df$lab_pre)

# Plot
quartz(width=8, height=6)                   
plot <- plot(df.likert, text.size=4, plot.percents=T, centered=FALSE,   
                      colors=c("gray25","#CA0020", "#F4A582", "gray80", "#92C5DE", "#0571B0"))  +
         theme(text=element_text(size=14), legend.box.background=element_rect(color="white"),                          legend.title=element_text(size=8), legend.position="bottom", plot.title = element_text(hjust=0.5)) + 
         ylab("% of Participants") +
         guides(fill=guide_legend(nrow=2, title="", reverse=T)) +
         ggtitle("Title") +
         theme(axis.text.x=element_text(color="black"))

plot

我的情节是这样的: 结果图

4

1 回答 1

0

查看 的代码likert.bar.plot,似乎有一个奇怪的部分应该警告组+绘图百分比:

if (FALSE & plot.percents) {
            warning("plot.percents is not currenlty supported for grouped analysis.")
        }

基本上你可以重新计算文本的位置,然后用geom_text().Try 把它放回去。请注意你不需要这个库plyr,如果你已经加载了它,请确保它之前加载过dplyr,否则会导致很多问题:

library(ggplot2)
library(likert)
#library(plyr)
library(dplyr)

func = function(X){
offset=sum(X[X<0])
cumsum(abs(X))+offset - abs(X)/2
}

p <- plot(df.likert, text.size=4, plot.percents=TRUE)

label_data = p$data %>% 
group_by(Group,Item) %>% 
mutate(perc=round(abs(value),digits=1),value=func(value)) %>%
filter(perc!=0)

p + geom_text(data=label_data,aes(label=paste0(perc,"%")),size=2)

在此处输入图像描述

于 2020-02-22T23:42:56.970 回答