首页 > 解决方案 > 重新排序因子水平以在分面包裹的条形图中正确显示

问题描述

我正在尝试重新排序变量“响应”中的级别,以便它们在我的条形图上以正确的顺序显示。级别顺序应为“是”、“否”和“不到一年”、“一年”、“大于一年”。但是,当我尝试使用 factor() 函数对它们重新排序时,我的一些变量级别被替换为 NA。

在此处输入图像描述

这是我的代码:

library(tidyverse)
library(scales)

percent <- c(0.20, .56, .36, .36, .78, .64, 0.20)
response <- c(rep(c("yes", "no"), 2), c("less than one year", "one year", "greater than one year"))
question <- c(rep("dogs",2), rep("cats",2), rep("years at home",3)) 

survey <- data.frame(percent, response, question) %>% 
  mutate(response = str_wrap(response, width = 8)) %>% 
  mutate(response = factor(response, levels = c("yes", "no", "less than one year", "one year", "greater than one year")))

ggplot(survey, aes(x=response, y=percent)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(aes(label = scales::percent(percent),
                y= percent), position = position_dodge(width = 1), vjust = -.5) +
  scale_y_continuous(breaks = seq(0, 1.1,0.2),
                     limits = c(0,1.1),
                     labels=percent_format(accuracy = 1),
                     expand = c(0,0)) +
  labs(title = "",
       x = "",
       y = "Percentage") +
  facet_wrap(~question, scales = "free") +
  theme_bw() +
  theme(plot.title = element_text(family = "sans", 
                                  face = "bold", 
                                  hjust = 0.5, 
                                  size = 14, 
                                  margin = margin(0,0,10,0)),
        axis.text = element_text(family = "sans",
                                 size = 11),
        axis.text.y = element_text(margin = margin(0,0,0,5),
                                   size = 12),
        axis.text.x = element_text(size = 12,
                                   angle = 0,
                                   margin = margin(5,0,0,0)),
        axis.title.x = element_text(family = "sans",
                                    size = 14,
                                    margin = margin(10,0,0,0)),
        axis.title.y = element_text(family = "sans",
                                    size = 14),
        plot.caption = element_text(hjust = 0.5, vjust = -1.0, size = 12, 
                                    margin = margin(4,0,0,0)),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        strip.text = element_text(size = 11, face = "bold"))

标签: rggplot2

解决方案


响应变量中的值需要称为“小于\n一年\n年”和“大于\n大于一年”,因为它们包含换行符(“\n”)。这应该可以解决问题!

survey <- data.frame(percent, response, question) %>% 
  mutate(response = str_wrap(response, width = 8)) %>% 
  mutate(response = factor(response, levels = c("no", "yes", "less\nthan one\nyear", "one year", "greater\nthan one\nyear")))

如果这仍然没有提供正确的顺序,你可以as.ordered = T在你的因子函数中添加一个选项,但上面的例子似乎工作正常。


推荐阅读