【问题标题】:ggplot2 bar chart won't display spaces between barsggplot2条形图不会显示条之间的空格
【发布时间】:2016-01-14 07:43:06
【问题描述】:

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

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

我的雇主的平面设计政策是在条形之间留有少量分隔。但无论我将宽度参数设置为什么,生成的绘图都没有条形之间的空间。我应该使用其他参数来完成此操作吗?

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

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)

我会将它转换为一个因子,除了我想显示大小为 0.25 的箱 - 四分之一之间有少量值(如您在上面看到的,其中一个值为 5.625)。而stat_bin 仅适用于 ggplot 认为是连续的数据。

【问题讨论】:

  • 解决方案取决于数据的格式(因子、数字等)。您可以尝试在问题中包含一些数据 - 尝试粘贴到 dput(head(score.data)) 的输出中。如果你有整数作为你的score,你可以试试ggplot(data = score.data, aes(x = factor(score))) + geom_bar()
  • 请参阅here 以获取类似问题的答案。
  • 由于您还没有回复我的回答,我想知道它是否为您提供了所需的解决方案。
  • 是的,结果证明这对我需要做的事情很有效。谢谢。

标签: r ggplot2 histogram bar-chart


【解决方案1】:

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

# 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 在 cmets 中提到的技巧:

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

给出:

【讨论】:

    猜你喜欢
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多