如何解决ggplot中geom_bar条形图内部出现多余线条的问题
问题:ggplot geom_bar条形内部出现多余线条
使用geom_bar(stat = 'identity', color = "red")设置条形边缘颜色时,条形内部出现多余的红色线条,尝试position = "dodge"后问题仍存在。
相关数据与代码:
b <- structure(list(ForkLength = c(37, 36, 37, 35, 36, 35, 36, 36, 35, 35, 36, 37, 37, 37, 37, 36, 38, 36, 37, 37, 38, 38, 36, 35, 37, 36, 37, 37, 36, 36, 35, 38, 38, 37, 36, 35, 38, 38, 37, 37, 38, 36, 36, 38, 37, 37, 36, 37, 38, 37, 38, 37, 36, 38, 35, 38, 37, 39, 38, 37, 38, 38, 39, 39, 36, 38, 35, 37, 36, 39, 37, 39, 38, 37, 36, 37, 38, 36, 36, 38, 37, 37, 37, 38, 37, 38, 37, 39, 35, 39, 37, 38, 38, 38, 37, 38, 37, 35, 36, 40), Count = c(1, 2, 1, 1, 1, 1, 1, 2, 1, 4, 5, 2, 1, 1, 1, 1, 1, 1, 1, 4, 1, 1, 6, 3, 1, 1, 1, 3, 3, 1, 1, 1, 1, 2, 4, 1, 1, 5, 1, 1, 2, 1, 2, 1, 1, 2, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 3, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1)), row.names = c(NA, 100L), class = "data.frame") ggplot(b, aes(x = ForkLength ,y= Count)) + geom_bar(stat = 'identity', color = "red") + theme_classic()
(注:条形内部可见多条红色重叠线条,并非仅边缘着色)
解决方案
问题根源是你的数据中同一ForkLength对应多行记录,geom_bar(stat="identity")会为每行数据单独绘制一个条形,这些条形在同一x轴位置堆叠在一起,每个条形的红色边缘就会重叠显示为内部的线条。
有两种简单的解决方法:
方法1:先汇总数据
用dplyr先按ForkLength分组求和,再绘图:
library(dplyr) b_summary <- b %>% group_by(ForkLength) %>% summarise(total_count = sum(Count)) ggplot(b_summary, aes(x = ForkLength, y = total_count)) + geom_bar(stat = "identity", color = "red") + theme_classic()
方法2:直接用stat="summary"求和
无需提前汇总,在geom_bar中指定统计方法为求和:
ggplot(b, aes(x = ForkLength, y = Count)) + geom_bar(stat = "summary", fun = sum, color = "red") + theme_classic()
两种方法都能让同一ForkLength对应一个完整条形,红色仅显示在条形边缘,不会出现内部多余线条。
内容的提问来源于stack exchange,提问作者Salvador
相关产品推荐
相关产品推荐

