geom_histogram with subset data, how to stop bars overlapping

问题描述 投票:0回答:1

我正在探索跨年(1986-2023)的目标数据集(此处为目标/分钟),用于这项运动的男性和女性比赛。我想直观地探索两个游戏学科的数据子集(此处为 <=2009 and >2009)。

我试过的是这个

ggplot(WMGoalsAll,aes(x=GoalsMin,fill=Discipline))+
  geom_histogram(data= ~subset(., Year >"2014"),aes(y=..count..),
                 binwidth=0.02,colour="black",fill="tomato3",position=position_dodge2(preserve="single"))+ 
  geom_histogram(data= ~subset(., Year<="2014"),aes(y=..count..),
                 binwidth=0.02,position="dodge",colour="black",fill="powderblue")+
  facet_grid(Discipline~.,scales="free")+
  scale_x_continuous(breaks=seq(0,0.3,0.02))+theme_light()+theme(axis.text.x=element_text(angle=90,vjust=0.5))

这给了我想要的数字 Freq goals/min

... 除了如您所见,我无法弄清楚如何使用“position="dodge"”或其变体之一来使每个面的条形并排放置而不是位于顶部。我制作了数据的子集以构建单独的图形,然后将它们与 grid.arrange 放在一起,但我觉得比较不如 facet_grid 或 facet_wrap 那样清晰。感谢收到有关如何执行此操作的任何帮助。

r ggplot2 subset facet-grid geom-histogram
1个回答
0
投票

为了达到你想要的结果,使用完整的数据集,只使用一个

geom_histogram
而不是子集地图你想要在
fill
美学上分割数据的条件。之后你可以通过
scale_fill_manual
设置你想要的填充颜色。

使用一些虚假的随机示例数据:

set.seed(123)

WMGoalsAll <- data.frame(
  Year = sample(c(2010, 2020), 100, replace = TRUE),
  Discipline = sample(c("Men", "Women"), 100, replace = TRUE),
  GoalsMin = runif(100, 0, .3)
)

library(ggplot2)

ggplot(WMGoalsAll, aes(x = GoalsMin)) +
  geom_histogram(
    aes(fill = Year > 2014),
    binwidth = 0.02, colour = "black",
    position = position_dodge2(preserve = "single")
  ) +
  scale_x_continuous(breaks = seq(0, 0.3, 0.02)) +
  scale_fill_manual(values = c("tomato3", "powderblue")) +
  facet_grid(Discipline ~ ., scales = "free") +
  theme_light() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

© www.soinside.com 2019 - 2024. All rights reserved.