我有以下数据和代码:
# Load libraries and data.
library(tidyverse)
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)
)
# Organise data for plotting.
proportions <- df %>%
group_by(Category, Sub_Category) %>%
summarise(Proportion = mean(Fibre == TRUE) * 100, .groups = 'drop')
# Plot data.
ggplot(data = proportions,
aes(x = Proportion,
y = interaction(Sub_Category, Category),
fill = Category)
) +
geom_col(position = "dodge") +
scale_y_discrete(limits = rev) +
labs(fill = "Category")
它会产生输出:
Y轴标签包括Category和Sub_Category数据(例如布朗和面包).我希望他们只包括Sub_Category数据(即只包括棕色或白色或全麦等,与图例给出的类别数据).
How can I adjust the y-axis labels to remove the category information and keep the sub-category information?
理想情况下,解决方案应该是程序化的(而不是手动编辑y标签),因为我的实际数据具有比本例多得多的类别和子类别.