I'd like to make a slopegraph, along the lines (no pun intended) of this. Ideally, I'd like to do it all in a dplyr-style chain, but I hit a snag when I try to subset the data to add specific geom_text
labels. Here's a toy example:
# make tbl:
df <- tibble(
area = rep(c("Health", "Education"), 6),
sub_area = rep(c("Staff", "Projects", "Activities"), 4),
year = c(rep(2016, 6), rep(2017, 6)),
value = rep(c(15000, 12000, 18000), 4)
) %>% arrange(area)
# plot:
df %>% filter(area == "Health") %>%
ggplot() +
geom_line(aes(x = as.factor(year), y = value,
group = sub_area, color = sub_area), size = 2) +
geom_point(aes(x = as.factor(year), y = value,
group = sub_area, color = sub_area), size = 2) +
theme_minimal(base_size = 18) +
geom_text(data = dplyr::filter(., year == 2016 & sub_area == "Activities"),
aes(x = as.factor(year), y = value,
color = sub_area, label = area), size = 6, hjust = 1)
But this gives me Error in filter_(.data, .dots = lazyeval::lazy_dots(...)) :
object '.' not found
. Using subset instead of dplyr::filter
gives me a similar error. What I've found on SO/Google is this question, which addresses a slightly different problem.
What is the correct way to subset the data in a chain like this?
Edit: My reprex is a simplified example, in the real work I have one long chain. Mike's comment below works for the first case, but not the second.
.
withdf
?df %>% filter(area == "Health") %>% { ggplot(.) + geom_line(aes(x = as.factor(year), y = value, group = sub_area, color = sub_area), size = 2) + geom_point(aes(x = as.factor(year), y = value, group = sub_area, color = sub_area), size = 2) + geom_text(data = dplyr::filter(., year == 2016 & sub_area == "Activities"), aes(x = as.factor(year), y = value, color = sub_area, label = area), size = 6, hjust = 1) }
I'm not sure it gives you what you want, but it's a plot, at least.aes()
(my real example is one long pipe, the dataframe is not created first). But thanks, that works when the data is in the global environment.?magrittr::`%>%`
. Normally pipes pass the result of the left-hand side to the first parameter of the right-hand side, but if you wrap the RHS in braces, it will only send the result to wherever you put the.
, which lets you use it repeatedly or across multiple calls within a sub-pipeline.