使用ggplot2调整条形图标签、配色及添加图例的技术求助
完整实现代码
# 加载依赖包 library(tidyverse) library(scales) # 原始数据 dat <- read.table(text = " item_1 item_2 item_3 item_4 item_5 StronglyAgree 40 30 20 10 45 Agree 30 30 45 30 5 Netural 20 20 5 10 25 Disagree 5 10 8 25 15 StronglyDisagree 5 10 15 25 10",sep = "",header = TRUE) # 数据重构,设置态度的因子顺序和中文标签 datm <- dat %>% rownames_to_column("attitude") %>% mutate(attitude = factor(attitude, levels = c("StronglyDisagree", "Disagree", "Netural", "Agree", "StronglyAgree"), labels = c("非常不同意", "不同意", "中立", "同意", "非常同意"))) %>% pivot_longer(cols = starts_with("item"), names_to = "item", values_to = "value") # 绘图 ggplot(datm, aes(x = item, y = value, fill = attitude)) + geom_bar(position = "fill", stat = "identity") + # 替换item为实际问题文本,按需修改labels内容即可 scale_x_discrete(labels = c( "item_1" = "实际问题1文本", "item_2" = "实际问题2文本", "item_3" = "实际问题3文本", "item_4" = "实际问题4文本", "item_5" = "实际问题5文本" )) + # 自定义配色:红-灰-绿系 scale_fill_manual(values = c( "非常不同意" = "#a61c00", "不同意" = "#e06666", "中立" = "#939393", "同意" = "#93c47d", "非常同意" = "#38761d" )) + scale_y_continuous(labels = percent_format()) + labs(fill = "态度分类") + # 设置图例标题 coord_flip()
需求对应实现说明
- 替换item默认名称:通过
scale_x_discrete的labels参数实现编码到实际问题文本的映射,直接修改labels内的对应值即可匹配你的真实问题。 - 自定义配色:通过
scale_fill_manual手动指定每个态度分类对应的色值,可根据需求调整具体色号,保持红、灰、绿的色系对应即可。 - 显示分类图例:移除了原代码中
geom_bar里的show.legend = FALSE参数,同时通过labs参数可自定义图例标题。
内容的提问来源于stack exchange,提问作者Dr. Know Nothing
相关产品推荐
相关产品推荐

