我正在尝试创建两个图表,这些图表应按递减顺序显示频率。
#preparing the data to resemble actual data
test <- data.frame(HairEyeColor) %>%
mutate(combi = paste(Hair,Eye)) %>%
group_by(Sex) %>%
mutate(prop = Freq / sum(Freq)) %>%
ungroup()
test$combi <- factor(test$combi)
freq_test_count <- test %>%
setorder(Freq)
#creating the plot
freq_test_plot <- freq_test_count %>%
ggplot(aes(x = reorder(combi,prop),y = prop, label = Freq)) +
geom_col(show.legend = FALSE) +
geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) +
facet_wrap(~Sex, scales = "free") +
labs(y = "Proportion",
x = NULL) +
coord_flip()
当我绘制freq_test_plot时,它显示的是情节,但output is not in decreasing order
我不知道该怎么办才能看到频率降序的条件。
答案 0 :(得分:2)
解决方法是创建两个不同的图并将它们排列在网格中。但是你应该谨慎,因为like Gregor mentioned,它肯定会产生误导。
library(grid)
p1 = freq_test_count[freq_test_count$Sex == "Male",] %>%
ggplot(aes(x = reorder(combi,prop),y = prop, label = Freq)) +
geom_col(show.legend = FALSE) +
geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) +
facet_wrap(~Sex, scales = "free") +
labs(y = "Proportion",
x = NULL) +
coord_flip()
p2 = freq_test_count[freq_test_count$Sex == "Female",] %>%
ggplot(aes(x = reorder(combi,prop),y = prop, label = Freq)) +
geom_col(show.legend = FALSE) +
geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) +
facet_wrap(~Sex, scales = "free") +
labs(y = "Proportion",
x = NULL) +
coord_flip()
graphics.off()
grid.newpage()
grid.draw(ggarrange(p1, p2, ncol = 2))
答案 1 :(得分:1)
另一种解决方法是使该因素的男性和女性特定水平。在这里,我在男性头发/眼睛标签的前面添加了一个空格" "
。这允许您定义考虑性别的排序:
test <- data.frame(HairEyeColor) %>%
mutate(combi = paste(Hair,Eye)) %>%
group_by(Sex) %>%
mutate(prop = Freq / sum(Freq)) %>%
ungroup() %>%
mutate(combi = factor(test$combi),
sex_combi = factor(paste(ifelse(Sex == "Male", " ", ""), Hair, Eye)),
sex_combi = reorder(sex_combi, prop))
#creating the plot
ggplot(test, aes(x = sex_combi,y = prop, label = Freq)) +
geom_col(show.legend = FALSE) +
geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) +
facet_wrap(~Sex, scales = "free") +
labs(y = "Proportion",
x = NULL) +
coord_flip()
但正如我在评论中提到的,我认为这是一个误导性的情节。
答案 2 :(得分:0)
您是否希望对男性或女性进行排序?
library(tidyverse)
#preparing the data to resemble actual data
test <- data.frame(HairEyeColor) %>%
mutate(combi = paste(Hair,Eye)) %>%
group_by(Sex) %>%
mutate(prop = Freq / sum(Freq)) %>%
ungroup()
test$combi <- factor(test$combi)
test$combi<- factor(test$combi, levels = unique(test$combi)[order(test$Freq)],)
#creating the plot
ggplot(test,aes(x = combi,y = prop, label = Freq))+
geom_col(show.legend = FALSE)+
geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) +
facet_wrap(~Sex, scales = "free")+
labs(y = "Proportion",
x = NULL) +
coord_flip()
已更新,以包含问题的完整代码。