R ggplot柱状图仅高亮Prime分类时无该值全高亮问题求助
问题原因
当绘制的目标列不存在「Prime」值时,ifelse判断返回的填充类别只有Normal一种,ggplot默认会将调色板的第一个颜色映射给仅有的类别,刚好对应预设的高亮色,就出现了所有柱体全高亮的错误。
解决方案
显式指定填充色的固定映射关系,不管Highlighted类别是否存在,都绑定固定的颜色值,避免默认调色板的自动匹配错误。只需在每个ggplot语句中添加scale_fill_manual()配置即可。
修正后完整代码
library(ggplot2) library(gridExtra) test.df <- data.frame( replace_punct = c("Prime", "Not Measured", "Not Measured", "Not Measured", "Not Measured", "Not Measured", "Not Measured", "Not Measured"), pos = c("Measured", "Not Measured", "Not Measured", "Not Measured", "Not Measured", "Not Measured", "Not Measured", "Not Measured"), spelling_corr = c("Measured", "Not Measured", "Not Measured", "Not Measured", "Not Measured", "Not Measured", "Prime", "Prime"), stringsAsFactors = FALSE ) # 公共填充色配置,可根据需求自行修改颜色值 fill_map <- c("Highlighted" = "#E41A1C", "Normal" = "#999999") replace_punct_bar <- ggplot(data=test.df, aes(x = replace_punct, y = after_stat(count/sum(count)), fill = ifelse(replace_punct == "Prime", "Highlighted", "Normal"))) + scale_y_continuous(labels = scales::percent) + geom_bar() + scale_fill_manual(values = fill_map) + # 新增固定填充映射 labs(title = "Replace punctuation freq", y = "Percent", x = "Status") + geom_hline(aes(yintercept=0.6), colour="#990000", linetype="dashed") + theme(legend.position="none") pos_bar <- ggplot(data=test.df, aes(x = pos, y = after_stat(count/sum(count)), fill = ifelse(pos == "Prime", "Highlighted", "Normal"))) + scale_y_continuous(labels = scales::percent) + geom_bar() + scale_fill_manual(values = fill_map) + # 新增固定填充映射 labs(title = "Part of speech freq", y = "Percent", x = "Status") + geom_hline(aes(yintercept=0.6), colour="#990000", linetype="dashed") + theme(legend.position="none") spelling_corr_bar <- ggplot(data=test.df, aes(x = spelling_corr, y = after_stat(count/sum(count)), fill = ifelse(spelling_corr == "Prime", "Highlighted", "Normal"))) + scale_y_continuous(labels = scales::percent) + geom_bar() + scale_fill_manual(values = fill_map) + # 新增固定填充映射 labs(title = "Spelling correction freq", y = "Percent", x = "Status") + geom_hline(aes(yintercept=0.6), colour="#990000", linetype="dashed") + theme(legend.position="none") grid.arrange(replace_punct_bar, pos_bar, spelling_corr_bar, ncol=3)
可选优化
如果需要批量生成多个同类型的柱状图,可以封装为函数减少重复代码:
plot_bar <- function(col_name, title) { ggplot(data=test.df, aes(x = .data[[col_name]], y = after_stat(count/sum(count)), fill = ifelse(.data[[col_name]] == "Prime", "Highlighted", "Normal"))) + scale_y_continuous(labels = scales::percent) + geom_bar() + scale_fill_manual(values = fill_map) + labs(title = title, y = "Percent", x = "Status") + geom_hline(aes(yintercept=0.6), colour="#990000", linetype="dashed") + theme(legend.position="none") } # 调用函数生成三个图 replace_punct_bar <- plot_bar("replace_punct", "Replace punctuation freq") pos_bar <- plot_bar("pos", "Part of speech freq") spelling_corr_bar <- plot_bar("spelling_corr", "Spelling correction freq")
内容的提问来源于stack exchange,提问作者Haza
相关产品推荐
相关产品推荐

