本文介绍了为ggplot2中的每个面板添加一条具有不同截距的垂直线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我使用ggplot2来创建直方图的面板,我希望能够在每个组的平均值上添加一条垂直线。但geom_vline()为每个面板使用相同的截距(即全局平均值): $ p $ require(ggplot2)#设置一些样本数据 N cat1 val df< - data.frame(cat1,cat2,val) #绘制一个直方图,平均值为 qplot (val,data = df,geom =histogram,binwidth = 0.2)+ geom_vline(xintercept = mean(val),color =red) #绘制直方图在全局平均值为 qplot(val,data = df,geom =histogram,binwidth = 0.2,facets = cat1〜cat2)+ geom_vline(xintercept = mean(val),color =红色) 我如何才能使用每个面板的组均值作为x截距? (如果您也可以通过平均值的值添加文本标签,则可以获得奖励积分。) 解决方案一种方法是 library(reshape) dfs< - 重铸(data.frame(cat1,cat2,val),cat1 + cat2〜variable,fun.aggregate = mean) qplot(val,data = df,geom =直方图,binwidth = 0.2,facets = cat1〜 cat2)+ geom_vline(data = dfs,aes(xintercept = val),color =red)+ geom_text(data = dfs,aes(x = val + 1,y = 1,label = round(val,1)) ,size = 4,color =red) I'm using ggplot2 to create panels of histograms, and I'd like to be able to add a vertical line at the mean of each group. But geom_vline() uses the same intercept for each panel (i.e. the global mean):require("ggplot2")# setup some sample dataN <- 1000cat1 <- sample(c("a","b","c"), N, replace=T)cat2 <- sample(c("x","y","z"), N, replace=T)val <- rnorm(N) + as.numeric(factor(cat1)) + as.numeric(factor(cat2))df <- data.frame(cat1, cat2, val)# draws a single histogram with vline at meanqplot(val, data=df, geom="histogram", binwidth=0.2) + geom_vline(xintercept=mean(val), color="red")# draws panel of histograms with vlines at global meanqplot(val, data=df, geom="histogram", binwidth=0.2, facets=cat1~cat2) + geom_vline(xintercept=mean(val), color="red")How can I get it to use each panel's group mean as the x-intercept? (Bonus points if you can also add a text label by the line with the value of the mean.) 解决方案 One way is to construct the data.frame with the mean values before hand.library(reshape)dfs <- recast(data.frame(cat1, cat2, val), cat1+cat2~variable, fun.aggregate=mean)qplot(val, data=df, geom="histogram", binwidth=0.2, facets=cat1~cat2) + geom_vline(data=dfs, aes(xintercept=val), colour="red") + geom_text(data=dfs, aes(x=val+1, y=1, label=round(val,1)), size=4, colour="red") 这篇关于为ggplot2中的每个面板添加一条具有不同截距的垂直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 21:05
查看更多