根据我在上一篇文章中的回答,我已成功创建了一个非常漂亮的箱形图(按照我的用途),按因子分类并分箱: ggplot: arranging boxplots of multiple y-variables for each group of a continuous x
现在,我想根据每个箱图中的观察数量来定制x轴标签。
require (ggplot2)
require (plyr)
library(reshape2)
set.seed(1234)
x<- rnorm(100)
y.1<-rnorm(100)
y.2<-rnorm(100)
y.3<-rnorm(100)
y.4<-rnorm(100)
df<- (as.data.frame(cbind(x,y.1,y.2,y.3,y.4)))
dfmelt<-melt(df, measure.vars = 2:5)
dfmelt$bin <- factor(round_any(dfmelt$x,0.5))
dfmelt.sum<-summary(dfmelt$bin)
ggplot(dfmelt, aes(x=bin, y=value, fill=variable))+
geom_boxplot()+
facet_grid(.~bin, scales="free")+
labs(x="number of observations")+
scale_x_discrete(labels= dfmelt.sum)
dfmelt.sum只给出了每个箱子的观察总数,而不是每个箱子图。 Boxplots统计数据给出了每个箱图的观测数量。
dfmelt.stat<-boxplot(value~variable+bin, data=dfmelt)
dfmelt.n<-dfmelt.stat$n
但是如何为每个箱图添加刻度线和标签?
谢谢,新浪
更新
我一直在努力。最大的问题是在上面的代码中,每个方面只提供一个刻度标记。由于我还想绘制每个箱图的平均值,我使用交互分别绘制每个箱图,这也为每个箱图在x轴上添加了刻度标记:
require (ggplot2)
require (plyr)
library(reshape2)
set.seed(1234) x<- rnorm(100)
y.1<-rnorm(100)
y.2<-rnorm(100)
y.3<-rnorm(100)
y.4<-rnorm(100)
df<- (as.data.frame(cbind(x,y.1,y.2,y.3,y.4))) dfmelt<-melt(df, measure.vars = 2:5)
dfmelt$bin <- factor(round_any(dfmelt$x,0.5))
dfmelt$f2f1<-interaction(dfmelt$variable,dfmelt$bin)
dfmelt_mean<-aggregate(value~variable*bin, data=dfmelt, FUN=mean)
dfmelt_mean$f2f1<-interaction(dfmelt_mean$variable, dfmelt_mean$bin)
dfmelt_length<-aggregate(value~variable*bin, data=dfmelt, FUN=length)
dfmelt_length$f2f1<-interaction(dfmelt_length$variable, dfmelt_length$bin)
侧面:也许有更优雅的方式来结合所有这些互动。我很乐意改进。
ggplot(aes(y = value, x = f2f1, fill=variable), data = dfmelt)+
geom_boxplot()+
geom_point(aes(x=f2f1, y=value),data=dfmelt_mean, color="red", shape=3)+
facet_grid(.~bin, scales="free")+
labs(x="number of observations")+
scale_x_discrete(labels=dfmelt_length$value)
这为每个可以标记的箱图提供了刻度标记。但是,在scale_x_discrete中使用标签只会在每个方面重复dfmelt_length $ value的前四个值。
如何规避? 谢谢,新浪
答案 0 :(得分:10)
看看这个答案,它不在标签上,但它有效 - 我已经使用了这个
Modify x-axis labels in each facet
你也可以这样做,我也用过
library(ggplot2)
df <- data.frame(group=sample(c("a","b","c"),100,replace=T),x=rnorm(100),y=rnorm(100)*rnorm(100))
xlabs <- paste(levels(df$group),"\n(N=",table(df$group),")",sep="")
ggplot(df,aes(x=group,y=x,color=group))+geom_boxplot()+scale_x_discrete(labels=xlabs)
这也有效
库(GGPLOT2) 库(reshape2)
df <- data.frame(group=sample(c("a","b","c"),100,replace=T),x=rnorm(100),y=rnorm(100)*rnorm(100))
df1 <- melt(df)
df2 <- ddply(df1,.(group,variable),transform,N=length(group))
df2$label <- paste0(df2$group,"\n","(n=",df2$N,")")
ggplot(df2,aes(x=label,y=value,color=group))+geom_boxplot()+facet_grid(.~variable)