我想制作一个斜率图,沿着 this 的线条(没有双关语意) .理想情况下,我想在 dplyr 样式的链中完成所有操作,但是当我尝试对数据进行子集化以添加特定 geom_text
时遇到了障碍。标签。这是一个玩具示例:
# 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)
但这给了我
Error in filter_(.data, .dots = lazyeval::lazy_dots(...)) :
object '.' not found
.使用子集代替 dplyr::filter
给了我一个类似的错误。我在 SO/Google 上发现的是 this问题,它解决了一个稍微不同的问题。在这样的链中对数据进行子集化的正确方法是什么?
编辑 :我的reprex是一个简化的例子,在实际工作中我有一个长链。 Mike 下面的评论适用于第一种情况,但不适用于第二种情况。
最佳答案
如果您将绘图代码包装在 {...}
中,您可以使用 .
准确指定先前计算结果的插入位置:
library(tidyverse)
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)
df %>% filter(area == "Health") %>% {
ggplot(.) + # add . to specify to insert results here
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"), # and here
aes(x = as.factor(year), y = value,
color = sub_area, label = area), size = 6, hjust = 1)
}
虽然该图可能不是您真正想要的,但至少它会运行以便您可以对其进行编辑。
发生了什么:通常
%>%
将左侧 (LHS) 的结果传递给右侧 (RHS) 的第一个参数。但是,如果将 RHS 括在大括号中,%>%
只会将结果传递到您明确放置 .
的任何地方.这个公式对于嵌套的子管道或其他复杂的调用(如 ggplot 链)很有用,否则只能通过使用 .
重定向来解决这些调用。 .见 help('%>%', 'magrittr')
了解更多详情和选项。
关于r - 使用 ggplot2 在 dplyr 链中设置子集/过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44007998/