在每个方面而不是整体上显示摘要行 [英] Display a summary line per facet rather than overall
问题描述
我正在尝试类似于此问题,但希望在单个块中完成此操作,而不是分别缓存值.
I am trying to do something similar to this question, but hoping to do it in a single block rather than caching values separately.
我正在创建与此类似的图表:
I am creating a chart similar to this:
library(tidyverse)
mtcars %>%
rownames_to_column("carmodel") %>%
mutate(brand = substr(carmodel, 1, 4)) %>%
group_by(brand, cyl) %>%
summarize(avgmpg = mean(mpg)) %>%
ggplot(aes(x=brand, y = avgmpg)) +
geom_point() +
facet_grid(cyl~., scales = "free_y") +
coord_flip()
按一个字段分组,然后在结果上绘制计算出的summarize()
值,并使用构面将相似的观察值放在一起.我想做的是在每个构面中添加一条线,以显示该构面的观测值的平均值.我尝试将geom_hline(aes(yintercept = mean(avgmpg)))
添加到定义中,但是它返回整个数据集的平均值,而不是构面中的观察值:
Grouping by one of the fields, and then charting a calculated summarize()
value on the result, using facets to place similar observations together. What I would like to do is add a line in each facet showing the mean of the observations for that facet. I have tried adding geom_hline(aes(yintercept = mean(avgmpg)))
to the definition, but it returns the mean for the entire dataset, not the observations in the facet:
我追求的是这样的. (这里的线是用图像编辑器绘制的.)
What I'm after is more like this. (The lines here are drawn with an image editor.)
这可能吗?
推荐答案
由于您说过要在一个块中完成,请注意,在.
的许多用法中,您可以在几何图形中使用它来引用原始的ggplot()
的数据参数.因此,您可以在此处进行其他汇总以获取geom_vline
的值.我也只是颠倒了geom_point
中的美观,而不是使用coord_flip
.
Because you said you wanted to do it in one block, note that among the many uses of .
you can use it in geoms to refer to the original data argument to ggplot()
. So here you can do an additional summarise to get the values for geom_vline
. I also just reversed the aesthetics in geom_point
instead of using coord_flip
.
library(tidyverse)
mtcars %>%
rownames_to_column("carmodel") %>%
mutate(brand = substr(carmodel, 1, 4)) %>%
group_by(brand, cyl) %>%
summarize(avgmpg = mean(mpg)) %>%
ggplot(aes(y=brand, x = avgmpg)) +
geom_point() +
geom_vline(
data = . %>%
group_by(cyl) %>%
summarise(line = mean(avgmpg)),
mapping = aes(xintercept = line)
) +
facet_grid(cyl~., scales = "free_y")
reprex软件包(v0.2.0)于2018-06-21创建.
Created on 2018-06-21 by the reprex package (v0.2.0).
这篇关于在每个方面而不是整体上显示摘要行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!