我有以下数据集:
df <- data.frame(
Product = c(755, 728, 417, 355, 913, 634, 385, 208, 204, 696, 968, 816, 279, 869, 823, 646, 986, 674, 806, 335, 731, 734, 107, 105, 512, 859, 159, 113, 353, 105, 205, 919, 243, 717, 838, 408, 423, 357, 408, 464, 724, 643, 943, 648, 623, 451, 449, 135, 842, 711),
Category = c("Bread", "Cheese", "Bread", "Cheese", "Bread", "Cheese", "Bread", "Bread", "Bread", "Cheese", "Bread", "Bread", "Cheese", "Bread", "Cheese", "Bread", "Bread", "Bread", "Cheese", "Cheese", "Cheese", "Bread", "Bread", "Cheese", "Bread", "Cheese", "Bread", "Bread", "Bread", "Cheese", "Cheese", "Bread", "Bread", "Cheese", "Cheese", "Bread", "Bread", "Bread", "Bread", "Cheese", "Cheese", "Cheese", "Cheese", "Cheese", "Cheese", "Cheese", "Cheese", "Bread", "Bread", "Cheese"),
Sub_Category = c("White", "Camembert", "White", "Camembert", "White", "Brie", "Brown", "Wholemeal", "White", "Brie", "Wholemeal", "Wholemeal", "Gouda", "Wholemeal", "Camembert", "Brown", "White", "Wholemeal", "Gouda", "Gouda", "Brie", "Wholemeal", "Wholemeal", "Camembert", "White", "Brie", "Wholemeal", "Wholemeal", "Brown", "Brie", "Brie", "White", "Wholemeal", "Camembert", "Gouda", "White", "Wholemeal", "Brown", "White", "Camembert", "Brie", "Brie", "Camembert", "Brie", "Camembert", "Gouda", "Camembert", "Wholemeal", "White", "Camembert"),
Fibre = c(TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE)
)
我有以下脚本来制作一个情节:
library(tidyverse)
proportions <- df %>%
group_by(Category, Sub_Category) %>%
summarise(Proportion = mean(Fibre == TRUE) * 100, .groups = 'drop')
ggplot(data = proportions, aes(x = Proportion, y = Sub_Category, fill = Category)) +
geom_col(position = "dodge") +
labs(fill = "Category")
这与我所期望的输出非常接近.
然而,我希望按类别对条块进行分组(所以所有的面包条都应该放在一起,然后再把cheese 条放在一起),并在分组后按降序排序.因此,从上到下依次为白色、全麦、棕色、布里干酪、卡门贝干酪、豪达干酪.
How can I reorder my bars so that they are grouped both by category and ordered by descending value?