当我在 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))
Run Code Online (Sandbox Code Playgroud)
如何在红/绿对组之间添加空白?
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))
Run Code Online (Sandbox Code Playgroud)
产生这个图:
geom_bargeom_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))
Run Code Online (Sandbox Code Playgroud)
产生这个图:
请让我知道这是否是您想要的。
| 归档时间: |
|
| 查看次数: |
5584 次 |
| 最近记录: |