-
Notifications
You must be signed in to change notification settings - Fork 2.1k

Description
I've got a feature request to give ggplot2 the ability to recognize dplyr::group_by()
.
library(tidyverse)
library(lubridate)
library(stringr)
df <-
tibble(Date = as.Date(0:364, origin = "2017-07-01"), Value = rnorm(365)) %>%
mutate(Year = str_sub(Date, 1, 4),
MoFloor = floor_date(Date, unit = "month")) %>%
group_by(Year, MoFloor) %>%
mutate(MoAvgValue = mean(Value)) %>%
ungroup() %>%
group_by(Year) %>%
mutate(MinMoFloor = min(MoFloor),
MaxMoFloor = max(MoFloor),
YearAvgValue = mean(MoAvgValue))
Let's first plot the data frame above.
ggplot(df, aes(MoFloor, MoAvgValue, group = Year)) +
facet_grid(~Year, scale = "free_x", space = "free_x") +
geom_point()
In my call to the facet_grid()
function I added the arguments scale = "free_x"
and space = "free_x"
to get rid of empty white space on the plots.
When I go ahead and add geom_segment()
s based on group_by()
d data, the scale = "free_x"
and space = "free_x"
arguments are negated. The empty white space reappears!
ggplot(df, aes(MoFloor, MoAvgValue, group = Year)) +
facet_grid(~Year, scale = "free_x", space = "free_x") +
geom_point() +
geom_segment(data = df,
aes(x = min(MinMoFloor),
y = YearAvgValue,
xend = max(MaxMoFloor),
yend = YearAvgValue))
My df
data frame is grouped by Year
. The geom_segment()
function does not recognize this when I enter (for example) the x = min(MinMoFloor)
argument. geom_segment()
is pulling the min(MinMoFloor)
from the global column, instead of the grouped column.
I know I could substitute a modified geom_hline()
function instead of geom_segment()
for a working solution, but my lines are sometimes diagonal. And sometimes I'll have 50+ of these facet panels in my visualization, so defining the values manually is not practical either.
Thanks for considering this feature.