如何在 r 中使用 ggplot 对双条进行排序?

How to sort the double bar using ggplot in r?

我正在学习 r,我在按升序或降序对双条进行排序时遇到问题,我想将图例设置在图的顶部,两种颜色分别代表一行和两列,例如示例:

标题Time

盒子颜色Breakfast盒子颜色Dinner

剧情在这里

这是我的数据框:

dat <- data.frame(
  time = factor(c("Breakfast","Breakfast","Breakfast","Breakfast","Breakfast","Lunch","Lunch","Lunch","Lunch","Lunch","Lunch","Dinner","Dinner","Dinner","Dinner","Dinner","Dinner","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
  class = c("a","a","b","b","c","a","b","b","c","c","c","a","a","b","b","b","c","c"))

这是我进行更改的代码:

dat %>% 
  filter(time %in% c("Breakfast", "Dinner")) %>%
  droplevels %>%
  count(time, class) %>% 
  group_by(time) %>% 
  mutate(prop = n/sum(n)) %>%
  ggplot(aes(x = class, y = prop, fill = time, label = scales::percent(prop))) +
  geom_col(position = 'dodge') +
  geom_text(position = position_dodge(width = 0.9), vjust = 0.5, size = 3) + 
  scale_y_continuous(labels = scales::percent)+
  coord_flip()

如有任何帮助,我们将不胜感激。

这样的应该和你问的差不多,欢迎追问

回答过程中参考的资源:http://www.sthda.com/english/wiki/ggplot2-legend-easy-steps-to-change-the-position-and-the-appearance-of-a-graph-legend-in-r-software

使用部分答案,您可以进一步研究 https://ggplot2.tidyverse.org/reference/theme.html

library(tidyverse)

dat <- data.frame(
  time = factor(c("Breakfast","Breakfast","Breakfast","Breakfast","Breakfast","Lunch","Lunch","Lunch","Lunch","Lunch","Lunch","Dinner","Dinner","Dinner","Dinner","Dinner","Dinner","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
  class = c("a","a","b","b","c","a","b","b","c","c","c","a","a","b","b","b","c","c"))


dat %>% 
  filter(time %in% c("Breakfast", "Dinner")) %>%
  droplevels %>%
  count(time, class) %>% 
  group_by(time) %>% 
  mutate(prop = n/sum(n)) %>%
  ggplot(aes(x = fct_reorder(class,prop), y = prop, fill = time, label = scales::percent(prop))) +
  geom_col(position = 'dodge') +
  geom_text(position = position_dodge(width = 0.9), vjust = 0.5, size = 3) + 
  scale_y_continuous(labels = scales::percent)+
  coord_flip() +
  labs(x = "class",fill = "Time") +
  theme(legend.position = "top", legend.direction="vertical", legend.title=element_text(hjust = 0.5,face = "bold",size = 12))

reprex package (v0.3.0)

于 2020-05-08 创建

要使图例标题高于图例键,需要对主题和指南进行一些额外的调整。

dat %>% 
  filter(time %in% c("Breakfast", "Dinner")) %>%
  droplevels %>%
  count(time, class) %>% 
  group_by(time) %>% 
  mutate(prop = n/sum(n)) %>%
  ggplot(aes(x = class, y = prop, fill = time, label = scales::percent(prop))) +
  geom_col(position = 'dodge') +
  geom_text(position = position_dodge(width = 0.9), vjust = 0.5, size = 3) + 
  scale_y_continuous(labels = scales::percent)+
  coord_flip() +
  theme(legend.position="top", legend.direction="vertical", legend.title=element_text(hjust = 0.5))+
  guides(fill = guide_legend(title = "Time", nrow = 1))