如何添加带有刻面R的线
所以我有一个刻面图,我希望能够添加线到它,每个刻面都会改变 代码如下:如何添加带有刻面R的线,r,ggplot2,facet,R,Ggplot2,Facet,所以我有一个刻面图,我希望能够添加线到它,每个刻面都会改变 代码如下: p <- ggplot(mtcars, aes(x=wt))+ geom_histogram(bins = 20,aes(fill = factor(cyl)))+ facet_grid(.~cyl)+ scale_color_manual(values = c('red','green','blue'))+ geom_vline(xintercept = mean(mtcars$wt)) p p您
p <- ggplot(mtcars, aes(x=wt))+
geom_histogram(bins = 20,aes(fill = factor(cyl)))+
facet_grid(.~cyl)+
scale_color_manual(values = c('red','green','blue'))+
geom_vline(xintercept = mean(mtcars$wt))
p
p您可以使用ggstance
包中的stat\u summaryh
在ggplot调用中执行此操作。在下面的代码中,我还将scale\u color\u manual
更改为scale\u fill\u manual
,假设您试图设置直方图条的填充颜色:
library(tidyverse)
library(ggstance)
ggplot(mtcars, aes(x=wt))+
geom_histogram(bins = 20,aes(fill = factor(cyl)))+
stat_summaryh(fun.x=mean, geom="vline", aes(xintercept=..x.., y=0),
colour="grey40") +
facet_grid(.~cyl)+
scale_fill_manual(values = c('red','green','blue')) +
theme_bw()
另一种选择是计算几何线
内的所需平均值(这是@Ben建议的汇总方法的实现)。在下面的代码中,
是一个“代词”,指输入ggplot的数据帧(mtcars
):
ggplot(mtcars, aes(x=wt))+
geom_histogram(bins = 20,aes(fill = factor(cyl)))+
geom_vline(data = . %>% group_by(cyl) %>% summarise(wt=mean(wt)),
aes(xintercept=wt), colour="grey40") +
facet_grid(.~cyl)+
scale_fill_manual(values = c('red','green','blue')) +
theme_bw()
你会考虑单独计算(总结),然后将代码> xTopcP> < /代码>设置为吗?看起来这可能是合理的。可能是重复的