【发布时间】:2019-07-11 15:56:07
【问题描述】:
我正在尝试将 n 个连续的图排列成一个图矩阵。我首先通过运行一个 for 循环来获得这些图,但我不知道如何将它们排列成一个“图的图”。我使用了 par(mfrow=c(num.row,num.col)) 但它不起作用。还有 multiplot(plotlist = p, cols = 4) 和 plot_grid(plotlist = p)
#import dataset
Survey<-read_excel('datasets/Survey_Key_and_Complete_Responses_excel.xlsx',
sheet = 2)
#Investigate how the dataset looks like
glimpse(Survey)#library dplyr
#change data types
Survey$brand <- as.factor(Survey$brand)
Survey$zipcode <- as.factor(Survey$zipcode)
Survey$elevel <- as.factor(Survey$elevel)
Survey$car <- as.numeric(Survey$car)
#Relation brand-variables
p = list()
for(i in 1:ncol(Survey)) {
if ((names(Survey[i])) == "brand"){
p[[i]]<-ggplot(Survey, aes(x = brand)) + geom_bar() +
labs(x="Brand")
} else if (is.numeric(Survey[[i]]) == "TRUE"){
p[[i]]<-ggplot(Survey, aes(x = Survey[[i]], fill=brand)) + geom_histogram() +
labs(x=colnames(Survey[i]))
} else {
p[[i]]<-ggplot(Survey, aes(x = Survey[[i]], fill = brand)) + geom_bar() +
labs(x=colnames(Survey[i]))
}
}
我认为图表已正确附加到列表中,但我无法以矩阵形式绘制它们。
【问题讨论】:
-
您好,我认为
ggpubr包中的ggarrange()函数可能对您有用。它使在网格中排列图变得容易。 -
嗨@Knak,感谢您的评论。我试过调用 ggarrange(plotlist = p) 并收到以下错误:'错误:StatBin 需要一个连续的 x 变量:x 变量是离散的。也许你想要 stat="count"?'。谢谢:)
-
那么当你使用 plot_grid 时会发生什么?/
-
@ArthurYip 我得到与上面相同的错误。谢谢
-
@Marc 如果解决了您的问题,请接受该解决方案,谢谢!
标签: r for-loop matrix ggplot2 plot