Несколько гистограмм с ggplot2 и блестящей R - PullRequest
0 голосов
/ 05 апреля 2020

Я пытаюсь построить множественную гистограмму для набора данных об удовлетворенности клиентов, используя Ggplot на R Shiny. Удовлетворенность варьируется от 1 до 5, где 1 - самая низкая, а 5 - самая высокая. Вот как это выглядит: (Это образец исходного набора данных)

Satisfaction_Level <- c(4   ,4  ,5  ,5  ,3  ,4  ,4  ,4  ,4  ,5  ,1  ,4  ,1  ,3  ,4  ,4  ,1  ,4  ,4  ,1  ,4  ,4  ,4  ,4  ,2  ,4  ,2  ,4  ,3  ,1)

Location <- c("C"   ,"C"    ,"C"    ,"B"    ,"C"    ,"C"    ,"C"    ,"A"    ,"B"    ,"C"    ,"C"    ,"C"    ,"C"    ,"B"    ,"C"    ,"C"    ,"C"    ,"B"    ,"C"    ,"B"    ,"C"    ,"C"    ,"C"    ,"B"    ,"B"    ,"B"    ,"B"    ,"B"    ,"B"    ,"B")

С помощью приведенного ниже кода я смог сгенерировать этот график:

Overall satisfaction bar graph

#satisfaction counts
satisCounts <- data.frame(table(mydata[,1]))
colnames(satisCounts) <- c("satisLevel", "satisCount")
satisCounts$perc3 <- as.character(round(100* satisCounts$satisCount / sum(satisCounts$satisCount)), 2)
satisCounts$lab3 <- paste(satisCounts$satisCount, paste("(",satisCounts$perc3,"%)",sep=""),sep=" ")

output$graph3 <- renderPlot({
  satisCounts %>%
    ggplot(aes(x=satisLevel, y=satisCount)) +
    geom_bar(stat = "identity", aes(fill=satisLevel)) +
    labs(y= "Customer count", x="Satisfaction Level") +
    scale_fill_manual(values = c("#de425b", "#f2955a", "#ffe48f", "#a9b957", "#488f31")) +
    labs(fill = "Satisfaction Level") +
    geom_text(aes(label=lab3), vjust=-.5)
})

Но то, что я на самом деле хочу, это сделать эту гистограмму с несколькими уровнями удовлетворенности в зависимости от местоположения. Не могли бы вы помочь мне исправить это? Спасибо!

1 Ответ

1 голос
/ 05 апреля 2020

Из вашего вопроса не ясно, как должен выглядеть финальный сюжет. Одним из вариантов будет использование фацетирования. Другим вариантом будет использование точечной гистограммы. Но основная идея состоит в том, чтобы сначала рассчитать количество по уровням бездействия и удовлетворенности. Посмотри на это!

library(dplyr)
library(ggplot2)

Satisfaction_Level<-c(4 ,4  ,5  ,5  ,3  ,4  ,4  ,4  ,4  ,5  ,1  ,4  ,1  ,3  ,4  ,4  ,1  ,4  ,4  ,1  ,4  ,4  ,4  ,4  ,2  ,4  ,2  ,4  ,3  ,1)

Location <- c("C"  ,"C"    ,"C"    ,"B"    ,"C"    ,"C"    ,"C"    ,"A"    ,"B"    ,"C"    ,"C"    ,"C"    ,"C"    ,"B"    ,"C"    ,"C"    ,"C"    ,"B"    ,"C"    ,"B"    ,"C"    ,"C"    ,"C"    ,"B"    ,"B"    ,"B"    ,"B"    ,"B"    ,"B"    ,"B")

df <- data.frame(
  satisLevel = Satisfaction_Level,
  Location = Location,
  stringsAsFactors = FALSE
)

#satisfaction counts
# satisCounts <- data.frame(table(mydata[,1]))
# colnames(satisCounts) <- c("satisLevel", "satisCount")
# satisCounts$perc3 <- as.character(round(100* satisCounts$satisCount / sum(satisCounts$satisCount)), 2)
# satisCounts$lab3 <- paste(satisCounts$satisCount, paste("(",satisCounts$perc3,"%)",sep=""),sep=" ")

satisCounts <- df %>% 
  count(Location, satisLevel, name = "satisCount") %>% 
  mutate(satisLevel = factor(satisLevel))

satisCounts$perc3 <- as.character(round(100* satisCounts$satisCount / sum(satisCounts$satisCount)), 2)
satisCounts$lab3 <- paste(satisCounts$satisCount, paste("(",satisCounts$perc3,"%)",sep=""),sep=" ")

# Option 1: Use facetting
satisCounts %>%
  ggplot(aes(x=satisLevel, y=satisCount)) +
  geom_bar(stat = "identity", aes(fill=satisLevel)) +
  labs(y= "Customer count", x="Satisfaction Level") +
  scale_fill_manual(values = c("#de425b", "#f2955a", "#ffe48f", "#a9b957", "#488f31")) +
  labs(fill = "Satisfaction Level") +
  geom_text(aes(label=lab3), vjust=-.5) + 
  facet_wrap(~ Location, ncol = 1)

# Option 2: Dodged bar chart
satisCounts %>%
  ggplot(aes(x=Location, y=satisCount, fill=satisLevel)) +
  geom_bar(stat = "identity", position = position_dodge2(preserve = "single")) +
  labs(y= "Customer count", x="Satisfaction Level") +
  scale_fill_manual(values = c("#de425b", "#f2955a", "#ffe48f", "#a9b957", "#488f31")) +
  labs(fill = "Satisfaction Level") +
  geom_text(aes(label=lab3), vjust=-.5, position = position_dodge2(.9, preserve = "single"))

Создано в 2020-04-05 пакетом представ (v0.3.0)

...