使用HH包控制李克特图中的条形标签

时间:2019-04-03 16:17:02

标签: r graph label rstudio likert

我是R的初学者,正在使用RStudio创建带有条形图所示百分比的Likert图。一切正常,但“大多数时间”和“几乎总是”的百分比都没有在图形上的正确位置,这与正确显示的“很少”和“有时”的百分比不同。例如,S11的“大部分时间”应为28%,“几乎总是”为14%,但是该图显示“大部分时间”为14%,“几乎总是”为28%。

The graph

这是我的输入内容:

library(HH)

# store the original col names used in custom panel function
origNames = colnames(x)

# define a custom panel function
myPanelFunc <- function(...){
panel.likert(...)
vals <- list(...)
DF <- data.frame(x=vals$x, y=vals$y, groups=vals$groups)

### some convoluted calculations here...
grps <- as.character(DF$groups)
for(i in 1:length(origNames)){
grps <- sub(paste0('^',origNames[i]),i,grps)
}

DF <- DF[order(DF$y,grps),]

DF$correctX <- ave(DF$x,DF$y,FUN=function(x){
x[x < 0] <- rev(cumsum(rev(x[x < 0]))) - x[x < 0]/2
x[x > 0] <- cumsum(x[x > 0]) - x[x > 0]/2
return(x)
})

subs <- sub(' Positive$','',DF$groups)
collapse <- subs[-1] == subs[-length(subs)] & DF$y[-1] == DF$y[- 
length(DF$y)]
DF$abs <- abs(DF$x)
DF$abs[c(collapse,FALSE)] <- DF$abs[c(collapse,FALSE)] + 
DF$abs[c(FALSE,collapse)]
DF$correctX[c(collapse,FALSE)] <- 0
DF <- DF[c(TRUE,!collapse),]

DF$perc <- round(ave(DF$abs,DF$y,FUN=function(x){x/sum(x) * 100}), 0)


## Here goes 6 lines that have been changes - AK
# here we modify the column with labels a bit:
DF$perc <- paste0(DF$perc,'%')
# change all "0%" to blanks
DF$perc[DF$perc == "0%"] <- ""
# the argument label is a bit modified too
panel.text(x=DF$correctX, y=DF$y, label=DF$perc, cex=0.7)
}


# plot passing our custom panel function

p <- plot.likert(x, 
as.percent=TRUE, 
main = "Graph title",
positive.order = T,
ylab = "Question",    
key.border.white=F,
panel=myPanelFunc,
rightAxis=F, col = c("#FF7F00", "#FFBF80", "#C1E0F4", "#82C0E9")   
)

p

1 个答案:

答案 0 :(得分:0)

我认为问题出在第一行,请确保x替换为您的数据框的名称

origNames = colnames(x)