按递增顺序排列因素

Arranging factors in increasing order

我正在尝试创建两个图,它们应按降序显示频率。

#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

我不确定我应该怎么做才能看到按频率降序排列的术语。

解决方法是创建两个不同的图并将它们排列在网格中。但是你应该小心,因为,,它肯定会产生误导。

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))

您希望值按男性还是女性排序?

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()

已更新以包含问题的完整代码。

另一种解决方法是为该因素设置男性和女性特定水平。在这里,我在 Male Hair/Eye 标签的前面添加了一个 space " "。这使您可以定义考虑性别的排序:

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()

但正如我在评论中提到的,我认为这是一个误导性的情节。