我想在躲避的直方图中的每个垃圾箱之间填充,以便每个垃圾箱中的条清晰地分组在一起。如何使用ggplot
来做到这一点?
这是我的工作示例:
library(ggplot)
library(tidyverse)
diamonds %>%
filter(clarity %in% c("VS2", "VS1", "VVS2", "VVS1")) %>%
ggplot +
geom_histogram(
aes(x = price, fill = clarity),
breaks = seq(10000, 20000, 2500),
color = "black",
position = "dodge"
)
答案 0 :(得分:2)
直方图在条形图之间没有空格,只有条形图有空格。因此解决方案是改用geom_bar
。但是首先必须使用cut
手动对数据进行分箱。然后,通过设置position_dodge(width = 0.8)
来增加组中条形之间的间隔。
diamonds %>%
filter(clarity %in% c("VS2", "VS1", "VVS2", "VVS1")) %>%
mutate(price = cut(price, breaks = seq(250, 20000, 2500), labels = seq(250, 20000, 2500)[-1])) %>%
ggplot() +
geom_bar(
aes(x = price, fill = clarity),
width = 0.5,
color = "black",
position = position_dodge(width = 0.8)
)