备选方案 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))
生成此图:
请告诉我这是否是你想要的。