1

Limesurveyからエクスポートされた調査回答に基づいて、ggplot2 を使用してデータの棒グラフを作成しています。したがって、データには特定の形式があり、データ列にはいくつかの 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母音が省略されているため、ジェネリック関数を使用できません。...また、省略されたラベルの最後に3 つのドットを追加したいと考えています。だから私はカスタム関数を使用しようとしています。

以下は、この以前の投稿に基づいて解決策に最も近いものですが、エラーがスローされます。以下を参照してください。

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