如何在ggplot2中调整Y轴标签,仅保留子类别信息?
解决ggplot2 Y轴标签仅显示子类别问题
问题描述
使用interaction(Sub_Category, Category)作为Y轴变量时,Y轴标签会显示Sub_Category.Category的组合形式(如Brown.Bread),需求是仅显示Sub_Category名称,类别信息由图例展示,且方案需适配多类别/子类别场景。
解决方案
核心思路是直接将Sub_Category作为Y轴变量,通过position_dodge参数控制同子类别下不同类别的柱子并排,同时保留原有的轴顺序。修改后的完整代码如下:
# 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 with modified Y-axis ggplot(data = proportions, aes(x = Proportion, y = Sub_Category, fill = Category) ) + geom_col(position = position_dodge(width = 0.9)) + # 控制同子类别下柱子的间距 scale_y_discrete(limits = rev(unique(proportions$Sub_Category))) + # 保留原有的反转顺序 labs(fill = "Category", y = "Sub Category")
关键修改说明
- Y轴变量替换:将
y = interaction(Sub_Category, Category)改为y = Sub_Category,直接使用子类别作为Y轴标签。 - 调整柱子并排:使用
position_dodge(width = 0.9)替代position = "dodge",确保同一子类别下的不同类别柱子完全并排(width参数可根据需求微调)。 - 保留轴顺序:通过
rev(unique(proportions$Sub_Category))获取原数据中子类别的唯一值并反转,保持与原图表一致的Y轴顺序,无需手动指定标签。
内容的提问来源于stack exchange,提问作者Jay Bee
相关产品推荐
相关产品推荐

