【问题标题】:Spacing between groups of bars in histogram直方图中各组条形之间的间距
【发布时间】:2019-05-27 17:07:31
【问题描述】:

当我在条形位置为dodge 的 ggplot2 中生成直方图时,我希望在条形组之间有空间(即注意每组红/绿对之间的空白):

当我用连续数据构建直方图时,我很难产生相同的效果。我似乎无法在栏组之间添加空间,相反,所有内容都被挤压在一起。如您所见,比较红色/绿色对在视觉上很困难:

为了重现我的问题,我在这里创建了一个示例数据集:https://www.dropbox.com/s/i9nxzo1cmbwwfsa/data.csv?dl=0

要重现的代码:

data <- read.csv("https://www.dropbox.com/s/i9nxzo1cmbwwfsa/data.csv?dl=1")

ggplot(data, aes(x = soldPrice, fill = month)) +
    geom_histogram(binwidth=1e5, position=position_dodge()) +
    labs(x="Sold Price", y="Sales", fill="") +
    scale_x_continuous(labels=scales::comma, breaks=seq(0, 2e6, by = 1e5)) +
    theme_bw() +
    theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))

如何在红/绿对组之间添加空白?

【问题讨论】:

  • 我添加了一个没有重叠条的替代方案。请看一下。

标签: r ggplot2


【解决方案1】:

备选方案 1:与 geom_histogram() 重叠的条形图

来自?position_dodge()

Dodging preserves the vertical position of an geom while adjusting the horizontal position

此函数接受一个width 参数,用于确定要创建的空间。

要得到我认为你想要的,你需要为position_dodge() 提供一个合适的值。在你的情况下,binwidth=1e5,你可能会玩例如该值的 20%:position=position_dodge(1e5-20*(1e3))。 (我没有修改你的其余代码。)

您可以使用以下代码:

ggplot(data, aes(x = soldPrice, fill = month)) +
  geom_histogram(binwidth=1e5, position=position_dodge(1e5-20*(1e3))) + ### <-----
  labs(x="Sold Price", y="Sales", fill="") +
  scale_x_continuous(labels=scales::comma, breaks=seq(0, 2e6, by = 1e5)) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))

产生这个情节:

备选方案 2:使用 ggplot-object 并使用 geom_bar 进行渲染

geom_histogram() 的设计目的不是为了生产您想要的东西。另一方面,geom_bar() 提供了您所需的灵活性。

您可以使用geom_histogram 生成直方图并将其保存在 ggplot-object 中。然后,您使用ggplot_build() 生成绘图信息。现在, 您可以使用对象中的直方图绘制信息来生成带有geom_bar()的条形图

## save ggplot object to h
h <- ggplot(data, aes(x = soldPrice, fill = month)) + 
  geom_histogram(binwidth=1e5, position=position_dodge(1e5-20*(1e3)))

## get plotting information as data.frame
h_plotdata <- ggplot_build(h)$data[[1]]
h_plotdata$group <- as.factor(h_plotdata$group)
levels(h_plotdata$group) <- c("May 2018", "May 2019")

## plot with geom_bar
ggplot(h_plotdata, aes(x=x, y=y, fill = group)) +
  geom_bar(stat = "identity") +
  labs(x="Sold Price", y="Sales", fill="") +
  scale_x_continuous(labels=scales::comma, breaks=seq(0, 2e6, by = 1e5)) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))

生成此图:

请告诉我这是否是你想要的。

【讨论】:

  • 它越来越接近,但现在条形重叠。如果您查看我的第一个屏幕截图,您会看到条形组是并排的,没有重叠,然后组之间有空白区域。我尝试了position_dodge2(具有不同的padding 值),它添加了空白,但它没有将相关的条组合在一起。
  • 感谢备选方案 2。这是一些令人印象深刻的东西!我不知道你是怎么做到的,但它工作得很好。我必须了解更多关于ggplot_build 的信息。 :-)
  • 很高兴我能帮上忙。我也必须查一下,同时我也学到了一些;-)