I am a beginner in R and am using RStudio to create a likert graph with the percentages shown on the bars. Everything works fine, but none of the percentages of "most of the time" and "almost always" are in their right locations on the graph, unlike the percentages of "rarely" and "sometimes" that are shown correctly. For example, S11 should have 28% for "most of the time" and 14% for "almost always", but the graph shows 14% for "most of the time" and 28% for "almost always".
Here is my input:
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