尝试使用自定义函数在ggplot2

时间:2017-09-06 17:37:57

标签: r ggplot2 stringi

我使用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函数,因为它省略了元音;我还想在缩写标签的末尾添加三个点...。所以我试图使用自定义功能。

以下是我根据this earlier post得出的最接近解决方案,但它会引发错误,请参阅下文:

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 

我收到了以下错误,大概是因为&#34; NA&#34; (其他)数据中的响应。

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

有没有办法解决这个问题而无需更改基础数据?任何提示都将非常感谢!

0 个答案:

没有答案