1

我正在使用 ggplot2 根据从Limesurvey导出的调查响应创建数据条形图;因此数据具有特定的格式,并且数据列包含一些 NA(因为缺少响应或因为像下面的示例中那样标记了级别):

plotDf <- data.frame('Profession' = c('a', '-other-', 'c', 'd', 'a', 'g', 'd', 'a', 'c', 'e', '-oth-'))
plotDf[, 1] <- as.character(plotDf[, 1])
attributes(plotDf)$variable.labels[1] <- "What is your profession?"
plotDf[, 1] <- factor(plotDf[, 1], levels=c("a","b","c","d","e","f","g","h"),labels=c("Mayor", "Other elected local government representative", "Municipal or local government administration", "Municipal or local government technical department / engineer", "Staff from Central Authority / Ministry", "Development or Humanitarian Organization", "NGO", "Private sector"))
names(plotDf)[1] <- "Q1"
plotData <- plotDf[, 1]

将其绘制为条形图时,我想缩写 x 轴标签,因为响应选项很长。我不能使用通用abbreviate函数,因为它省略了元音;我还想...在缩写标签的末尾添加三个点。所以我正在尝试使用自定义函数。

以下是我最接近的解决方案,基于这个较早的帖子,但它会引发错误,见下文:

library(ggplot2)
library(stringi)

# Function to shorten label after maxlength
# but only shorten after whole words, and add "..."
shortenLabel <- function(x, maxlength) {
  result <- stri_extract_first_regex(x, paste0("^.{0,", maxlength, "}( |$)"))
  longer <- stri_length(x) > maxlength
  result[longer] <- stri_paste(result[longer], "...") # this produces the error
  result
}

myPlot <- ggplot(plotDf, aes(x=plotData, y=(..count..)/sum(..count..))) + 
  geom_bar(aes(y = (..count..)/sum(..count..), fill = plotData), position = "dodge") + 
  theme_set(theme_light()) +
  geom_text(aes(y = ((..count..)/sum(..count..)), label = scales::percent((..count..)/sum(..count..))), stat = "count", vjust = -0.5, hjust = 0.45) + 
  theme(axis.text.x = element_text(angle = 320, hjust = 0)) +
  scale_y_continuous(labels=scales::percent) +
  ggtitle("What is your profession?") +
  labs(x="", y="Percent", fill="Legend:") +
  scale_x_discrete(drop=FALSE, label=function(x) shortenLabel(x, 15)) + scale_fill_discrete(drop=FALSE)

myPlot 

我收到以下错误,大概是因为数据中的“NA”(其他)响应。

Error in result[longer] <- paste(result[longer], "...", sep = "") :
NAs are not allowed in subscripted assignments 

有没有办法解决这个问题而无需更改基础数据?任何提示将不胜感激!

4

0 回答 0