ggplot2 条形图不会显示条形之间的空格

ggplot2 bar chart won't display spaces between bars

我正在尝试在 ggplot2 中创建一个条形图,显示大型数据集的直方图。

ggplot(data = score.data, aes(x = score)) + geom_bar(binwidth = .25, width=.9)

我雇主的平面设计政策是在条形之间有少量的分隔。但无论我将 width 参数设置为什么,生成的图都不会在条形之间产生任何 space。我应该使用其他参数来完成此操作吗?

编辑:根据 jeremycg 在评论中的建议,我包含了一些我的数据。

score <- c(6.25, 4.75, 6, 1.5, 6, 5, 6, 2.75, 6, 2.5, 5.25, 6, 3.75, 6, 
           6.25, 5, 6.75, 2, 2.75, 3.25, 5.625, 6.5, 4, 5, 3)

我会将其转换为一个因子,但我想显示大小为 .25 的箱 - 四分之一之间有少量值(如您在上面所见,其中一个值为 5.625)。 stat_bin 仅适用于 ggplot 认为连续的数据。

假设您有数字数据而不是整数,您可以在 geom_bargeom_histogram 中设置 colour = "white"size = 1.5(或其他值)。这将使条形的边缘变白变粗(使用 size 参数),从而在它们之间创建一些视觉效果 space:

# create some sample data
set.seed(2)
data <- data.frame(score=rnorm(1000,0,5), int.score=sample(1:10,1000,replace=TRUE))

# create the plot
ggplot(data, aes(x = score)) + 
  geom_bar(binwidth = .25, color="white", size=1.5) +
  theme_bw()

这给出:

当你有整数时,你也可以使用@jeremycg 在评论中提到的技巧:

ggplot(data, aes(x = factor(int.score))) + 
  geom_bar(width=0.7) +
  theme_bw()

给出: