我想为连续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))
Run Code Online (Sandbox Code Playgroud)
然后我融化了
dfmelt <- melt(df, measure.vars=2:5)
Run Code Online (Sandbox Code Playgroud)
这个解决方案 中显示的facet_wrap(ggplot(facets)中的因子多个绘图)给出了单个图中的每个变量,但是我希望每个变量的箱形图彼此相邻,每个x的bin都在一个图.
ggplot(dfmelt, aes(value, x, group = round_any(x, 0.5), fill=variable))+
geom_boxplot() +
geom_jitter() +
facet_wrap(~variable)
Run Code Online (Sandbox Code Playgroud)
这显示了y变量彼此相邻但不是bin x.
ggplot(dfmelt) +
geom_boxplot(aes(x=x,y=value,fill=variable))+
facet_grid(~variable)
Run Code Online (Sandbox Code Playgroud)
现在我想为x的每个bin生成这样的图.
什么必须改变或添加?
我有这个图表 - 我想在每个标签上添加文字N=xx来表示观察次数.我知道如何做到这一点,我已经在没有方面的图表上做到了.
当我在分面图表上尝试它时它不起作用(我在所有3个图表上的开放式刻度上获得了相同的N,在受限制的图表上获得相同的N等)
我希望有人可以指出解决方案,如何控制给定方面的元素?
library(ggplot2)
library(scales)
stat_sum_single <- function(fun, geom="point", ...) {
stat_summary(fun.y=fun, fill="red", geom=geom, size = 5, shape=24)
}
set.seed(1)
data1 <- data.frame(Physicians_In=sample(1:3,100,replace=T),Physicians_Out=sample(1:3,100,replace=T),share=runif(100,0,1))
data1$Physicians_In <- factor(data1$Physicians_In,levels=c(1,2,3),labels=c("Open","Restricted","Closed"))
data1$Physicians_Out <- factor(data1$Physicians_Out,levels=c(1,2,3),labels=c("Open","Restricted","Closed"))
access_ch3 <- ggplot(data1,aes(x=Physicians_In,y=share,fill=Physicians_In))+geom_boxplot()+stat_sum_single(mean)
access_ch3 <- access_ch3 +geom_jitter(position = position_jitter(width = .2),color="blue")+theme_bw()
access_ch3 <- access_ch3 + theme(legend.position="none") +scale_y_continuous("Gammagard Share",labels=percent)
gpo_labs5 <- paste(gsub("/","-\n",names(table(data1$Physicians_Out)),fixed=T),"\n(N=",table(data1$Physicians_Out),")",sep="")
access_ch3 <- access_ch3 + scale_x_discrete("Physician Access (In Hospital)",labels=gpo_labs5)
access_ch3 <- access_ch3 +facet_grid(.~Physicians_Out,labeller=label_both)
access_ch3
Run Code Online (Sandbox Code Playgroud)
我尝试创建9个标签并将该向量传递给scale_x_discrete元素,这只是回收了前3个,所以它也没有解决问题.