我花费了很多时间尝试将11个图形适配到一个图中,并使用
我有11种钻石分类(称为
我一直在尝试找到一个好的示例来重新创建我的数据框,但也失败了。我希望这个数据框可以帮助理解我要做什么,但我无法让它像我的数据框那样工作,并且一些图没有足够的数据,但重要的是使用
gridExtra
排列它们,但是我失败了,所以我求助于您希望您能帮忙。我有11种钻石分类(称为
size1
),还有另外11个分类(size2
),我想绘制每个增加的size1
和增加的clarity
(从1到6)的中位数价格随着钻石增加的size2
变化的情况,并在同一图中绘制所有11个图。我尝试使用其他帖子中建议的gridExtra
,但图例太远了,而且所有图都被挤到了左边,请问您能否帮我找出如何指定gridExtra
中“widths”的好方法?我找不到任何好的解释。非常感谢您的帮助,我真的很感激...我一直在尝试找到一个好的示例来重新创建我的数据框,但也失败了。我希望这个数据框可以帮助理解我要做什么,但我无法让它像我的数据框那样工作,并且一些图没有足够的数据,但重要的是使用
gridExtra
排列图形(如果您对其他部分有评论,请告诉我)。library(ggplot2)
library(gridExtra)
df <- data.frame(price=matrix(sample(1:1000, 100, replace = TRUE), ncol = 1))
df$size1 = 1:nrow(df)
df$size1 = cut(df$size1, breaks=11)
df=df[sample(nrow(df)),]
df$size2 = 1:nrow(df)
df$size2 = cut(df$size2, breaks=11)
df=df[sample(nrow(df)),]
df$clarity = 1:nrow(df)
df$clarity = cut(df$clarity, breaks=6)
# Create one graph for each size1, plotting the median price vs. the size2 by clarity:
for (c in 1:length(table(df$size1))) {
mydf = df[df$size1==names(table(df$size1))[c],]
mydf = aggregate(mydf$price, by=list(mydf$size2, mydf$clarity),median);
names(mydf)[1] = 'size2'
names(mydf)[2] = 'clarity'
names(mydf)[3] = 'median_price'
assign(paste("p", c, sep=""), qplot(data=mydf, x=as.numeric(mydf$size2), y=mydf$median_price, group=as.factor(mydf$clarity), geom="line", colour=as.factor(mydf$clarity), xlab = "number of samples", ylab = "median price", main = paste("region number is ",c, sep=''), plot.title=element_text(size=10)) + scale_colour_discrete(name = "clarity") + theme_bw() + theme(axis.title.x=element_text(size = rel(0.8)), axis.title.y=element_text(size = rel(0.8)) , axis.text.x=element_text(size=8),axis.text.y=element_text(size=8) ))
}
# Couldnt get some to work, so use:
p5=p4
p6=p4
p7=p4
p8=p4
p9=p4
# Use gridExtra to arrange the 11 plots:
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
mylegend<-g_legend(p1)
grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
p2 + theme(legend.position="none"),
p3 + theme(legend.position="none"),
p4 + theme(legend.position="none"),
p5 + theme(legend.position="none"),
p6 + theme(legend.position="none"),
p7 + theme(legend.position="none"),
p8 + theme(legend.position="none"),
p9 + theme(legend.position="none"),
p10 + theme(legend.position="none"),
p11 + theme(legend.position="none"),
main ="Main title",
left = ""), mylegend,
widths=unit.c(unit(1, "npc") - mylegend$width, mylegend$width), nrow=1)
mylegendwidth
是一个向量,你可能想要使用sum(mylegend$width)
。 - baptiste