我花了很多時間試圖在一個地塊中安裝11個圖表並使用gridExtra
來排列它們,但是我失敗了,所以我希望你能幫上忙。使用gridExtra排列很多地塊
我的鑽石(稱之爲size1
)等11個類別(size2
)11個分類,我想通過增加size2
繪製平均價格爲每臺增加size1
和增加clarity
(從1到6)如何變化鑽石,並在同一圖表中繪製所有11個圖。 我嘗試使用gridExtra
建議在其他職位,但傳說是遠離右側,所有圖形都擠在左邊,請你幫我弄清楚如何在gridExtra
傳說的「寬度」必須指定?我找不到任何好的解釋。非常感謝你的幫助,我真的很感激它...
我一直在試圖找到一個很好的例子來重新創建我的數據框,但也失敗了。我希望這個數據框有助於理解我正在嘗試做什麼,我無法使其工作並與我的工作一樣,並且一些地塊沒有足夠的數據,但重要的部分是使用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 2013-02-18 18:59:05
謝謝baptiste,這個作品也是! – user971102 2013-02-22 16:52:17