gpt4 book ai didi

重新排序因子水平以在分面包装条形图中正确显示

转载 作者:行者123 更新时间:2023-12-04 10:45:53 26 4
gpt4 key购买 nike

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

enter image description here

这是我的代码:

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年”,因为它们包含换行符(“\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作为因子函数中的一个选项,但上面的示例似乎工作正常。

关于重新排序因子水平以在分面包装条形图中正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59709954/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com