我必须绘制很多直方图(数据集中每个变量一个),如下所示:
ggplot(data = df, aes(x = var)) +
geom_histogram(binwidth = 0.5) +
scale_x_continuous(breaks = seq(4, 16, 1), limits = c(4, 16)) +
geom_vline(aes(xintercept=mean(var)), color="red", linetype="dashed", size=1) +
geom_vline(aes(xintercept=median(var)), color="blue", size=1) +
geom_vline(aes(xintercept=quantile(var,0.25)), color="green", linetype="dotted", size=1) +
geom_vline(aes(xintercept=quantile(var,0.75)), color="green", linetype="dotted", size=1)
唯一认为变化是绑定宽度,中断和限制。 我可以在R中编写自定义函数,将所有这些geom_vline添加到任何绘图中并避免使用样板吗?
类似的东西:
ggplot(data = df, aes(x = var)) +
geom_histogram(binwidth = 0.5) +
scale_x_continuous(breaks = seq(4, 16, 1), limits = c(4, 16)) +
stat_lines(df, var)
我尝试返回所有geom_vline的连接但我得到:
Error in df[, var] : object of type 'closure' is not subsettable
答案 0 :(得分:0)
addGeomVline<-function(plot,...){
plot+geom_vline(...)
}
以下是有关如何使用它的示例
p<-qplot(x=1:3,y=1:3)
addGeomVline(p,xintercept = 5)