使用ggplot2手动调整条形图宽度:width参数无效求助
问题:geom_bar的width参数不生效,无法调窄条形宽度
尝试通过geom_bar的width参数调整条形图的条形宽度,但该参数并未生效,需要将条形设置得更窄。以下是使用的代码:
library(ggplot2) library(tidyverse) color_table <- tibble( Land_cover = c("A", "B", "C", "D"), Color = c("yellow", "darkgreen", "blue4", "maroon3") ) df <- data.frame( name=c("FM_BICEP","FM_NR","FM_TRICEP","FM_H_GRASP1","FM_CS_SPE","FM_MOS_SFL","FM_H_GRASP3*","FM_FS_RET","FM_W_SE3","FM_FS_ABD*","FM_MOS_SAB") , value=c(1.7,1.8,1.8,22.0,26.8,27.4,27.9,31.8,33.4,35.8,35.8), group=c("A","A","A","C","D","A","C","A","B","A","A") ) df$name <- factor(df$name, levels = df$name) df$group <- factor(df$group, levels = color_table$Land_cover) # Barplot ggplot(df, aes(x=name, y=value,fill = group)) + geom_bar(stat = "identity", aes(fill=group))+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+ scale_fill_manual(values = color_table$Color) + geom_col(width = 0.4)
原因分析
代码中同时调用了geom_bar(stat = "identity")和geom_col(),这两个函数功能完全重复——geom_col()本质就是geom_bar(stat = "identity")的简写。这导致你设置的width参数只作用在geom_col上,但geom_bar已经先绘制了一层默认宽度的条形,覆盖了geom_col的效果,所以看起来width参数没生效。
解决方案
删除其中一个重复的geom函数,将width参数放到保留的函数中即可:
方案1:保留geom_bar并设置width
library(ggplot2) library(tidyverse) color_table <- tibble( Land_cover = c("A", "B", "C", "D"), Color = c("yellow", "darkgreen", "blue4", "maroon3") ) df <- data.frame( name=c("FM_BICEP","FM_NR","FM_TRICEP","FM_H_GRASP1","FM_CS_SPE","FM_MOS_SFL","FM_H_GRASP3*","FM_FS_RET","FM_W_SE3","FM_FS_ABD*","FM_MOS_SAB") , value=c(1.7,1.8,1.8,22.0,26.8,27.4,27.9,31.8,33.4,35.8,35.8), group=c("A","A","A","C","D","A","C","A","B","A","A") ) df$name <- factor(df$name, levels = df$name) df$group <- factor(df$group, levels = color_table$Land_cover) # Barplot ggplot(df, aes(x=name, y=value,fill = group)) + geom_bar(stat = "identity", width = 0.4)+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+ scale_fill_manual(values = color_table$Color)
方案2:保留geom_col并设置width
library(ggplot2) library(tidyverse) color_table <- tibble( Land_cover = c("A", "B", "C", "D"), Color = c("yellow", "darkgreen", "blue4", "maroon3") ) df <- data.frame( name=c("FM_BICEP","FM_NR","FM_TRICEP","FM_H_GRASP1","FM_CS_SPE","FM_MOS_SFL","FM_H_GRASP3*","FM_FS_RET","FM_W_SE3","FM_FS_ABD*","FM_MOS_SAB") , value=c(1.7,1.8,1.8,22.0,26.8,27.4,27.9,31.8,33.4,35.8,35.8), group=c("A","A","A","C","D","A","C","A","B","A","A") ) df$name <- factor(df$name, levels = df$name) df$group <- factor(df$group, levels = color_table$Land_cover) # Barplot ggplot(df, aes(x=name, y=value,fill = group)) + geom_col(width = 0.4)+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+ scale_fill_manual(values = color_table$Color)
内容的提问来源于stack exchange,提问作者Ana
相关产品推荐
相关产品推荐

