首页 > 解决方案 > 直方图中各组条形之间的间距

问题描述

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

在此处输入图像描述

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

在此处输入图像描述

为了重现我的问题,我在这里创建了一个示例数据集: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))

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

标签: rggplot2

解决方案


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

来自?position_dodge()

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

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

要获得我认为您想要的,您需要为position_dodge(). 在您的情况下, where 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))

产生这个图:

在此处输入图像描述

请让我知道这是否是你想要的。


推荐阅读