r - 重新排序因子水平以在分面包裹的条形图中正确显示
问题描述
我正在尝试重新排序变量“响应”中的级别,以便它们在我的条形图上以正确的顺序显示。级别顺序应为“是”、“否”和“不到一年”、“一年”、“大于一年”。但是,当我尝试使用 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"))
解决方案
响应变量中的值需要称为“小于\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
在你的因子函数中添加一个选项,但上面的例子似乎工作正常。
推荐阅读
- google-chrome - 如何使用 chrome 扩展阻止脚本加载?
- python - 如何读取变量的名称python
- javascript - 在mac上运行离子应用程序时出错
- ruby - 如何在 Ruby 中捕获窗口屏幕截图
- java - 案例中如何使用涉及实例化的switch语句?
- node.js - 在节点 js 中找不到“nd sampleApp”命令
- javascript - 解析器(js)的正则表达式lookbehind替代
- python - 在 for 循环中生成时识别按钮
- puppet - puppet 资源如何在不编译失败的情况下检查 puppetmaster 上的数据源?
- c# - C#如何从IEnumerable中创建一个列表