R ggplot,用于交互作用的嵌套X轴()条形图中的因子变量
我如何格式化一个多面的、多组的方框图的x轴,这样我就可以得到像这样的东西(诡异的绘画,但显示了这个想法)。。。 这是到目前为止的代码R ggplot,用于交互作用的嵌套X轴()条形图中的因子变量,r,plot,ggplot2,axis,box,R,Plot,Ggplot2,Axis,Box,我如何格式化一个多面的、多组的方框图的x轴,这样我就可以得到像这样的东西(诡异的绘画,但显示了这个想法)。。。 这是到目前为止的代码 # Make the dataset data<-data.frame(cbind(runif(10,1,10), sample(1:5, 10, replace=TRUE), sample(1:5, 10, replace=TRUE),
# Make the dataset
data<-data.frame(cbind(runif(10,1,10),
sample(1:5, 10, replace=TRUE),
sample(1:5, 10, replace=TRUE),
sample(1:2, 10, replace=TRUE),
sample(1:2, 10, replace=TRUE)))
names(data)<-c("DV","Grouping_1", "Grouping_2", "Grouping_3", "Grouping_4")
data$Grouping_1<-as.factor(data$Grouping_1)
data$Grouping_2<-as.factor(data$Grouping_2)
data$Grouping_3<-as.factor(data$Grouping_3)
data$Grouping_4<-as.factor(data$Grouping_4)
# grab the interaction
data$groups<-interaction(data$Grouping_1,data$Grouping_2)
# Sort it (to make things neat)
data$groups<-factor(data$groups, levels = sort(levels(data$group)))
# Plot it
ggplot(data = data, aes(x =groups, y = DV, fill = Grouping_3)) +
geom_bar(stat = "identity", position = position_dodge()) + facet_grid(Grouping_4 ~ .)
#创建数据集
数据这在ggplot2
中不起作用。您可以尝试下面的代码。这真的不漂亮,但有点效果
gr <- as.numeric(as.character(data$groups))
# additional data for annotation
df_a <- data.frame(y=-Inf,
xmin = factor(sapply(1:5, function(x) min(gr[gr > x]))),
xmax = factor(sapply(2:6, function(x) max(gr[gr < x]))),
nr = -(sapply(1:5, function(x) sum(gr > x & gr < x+1))-1)*2.5+0.5, # change here to get horizontal adjustment right...
Grouping_4 = 2,
text = 1:5)
# Plot it
p <- ggplot(data = data, aes(x =groups, y = DV, fill = Grouping_3)) +
geom_bar(stat = "identity", position = position_dodge()) + facet_grid(Grouping_4 ~ .) +
geom_segment(data = df_a, aes(x=xmin, xend=xmax, y=y, yend=y, fill=NULL)) +
geom_text(data = df_a, aes(x=xmin, y=y+2, label=text, fill=NULL, hjust=nr), vjust = 1.5) +
theme(plot.margin = unit(c(1,1,2,1), "lines")) +
scale_x_discrete(name = "\ngroups", labels=paste0("\n\n", round(10 * (sort(gr)-round(sort(gr), 0)), 0)))
require(gridExtra)
# turns clipping off
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)
gr x&gr p你不能。ggplot2不支持多轴(有意)。如果你必须拥有它们,你可能需要在网格级别编辑grob(或者创建第二个grob并排列它们)。嗯,它不使用刻面,但也许你可以调整我在我的条形图中使用的xaxis的标签