带有ggplot的2 x 2绘图输出

时间:2018-02-25 12:48:35

标签: r plot ggplot2 grid

我有data.frame个以下变量:

centers.df <- data.frame(clust1 = sample(c(1,2), 50, replace=T), clust2 = sample(c(1,2), 50, replace =T), brand = sample(letters[1:4], 50, replace = T), cpal = sample(LETTERS[1:4], 50, replace = T), center = rnorm(100))

我想使用ggplot创建一个2x2的绘图输出。

到目前为止我做了什么:

plot_list <- vector("list", length = sum(length(unique(centers.df$clust1)), length(unique(centers.df$clust2)))
for (pl in 1:length(plot_list)) {
 for (i in 1:length(unique(centers.df$clust1))) {
  for (j in 1:length(unique(centers.df$clust2))) {  
  yrange <- range(centers.df$center)
  plot.df<- subset(centers.df, centers.df$clust1==i & centers.df$clust2==j)
  counts<- aggregate(plot.df$center, by=list(plot.df$cpal), FUN="sum")  
  g <- ggplot(counts, aes(counts[,1], counts[,2])) + geom_bar(stat = "identity") +
  theme(axis.title.x= element_blank(), axis.title.y= element_blank(),
        axis.text.x = element_text(color="#993333", size=14, angle=90),
        axis.line = element_line(colour = "darkblue",size = 1, linetype = "solid")) +
        ggtitle(paste0("Cluster ",i, ",", j, " #PoS ",length(res.som$Clusters[[i,j]])))
plot_list[[pl]] <- g 
  }
 } 
}

# grid.arrange(grobs=plot_list, nrow=2, ncol=2)

我想拥有什么:

 par(mfrow = c(length(unique(centers.df$clust1)), length(unique(centers.df$clust2))))
for (i in 1:length(unique(centers.df$clust1))) {
  for (j in 1:length(unique(centers.df$clust2))) {
   yrange <- range(centers.df$center)
   plot.df<- subset(centers.df, centers.df$clust1==i & centers.df$clust2==j)
   counts<- aggregate(plot.df$center, by=list(plot.df$cpal), FUN="sum")
   barplot(height = counts[,2], las=2, cex.names = 0.7, col= "darkblue", ylim=yrange, #yaxt="n",
        names.arg=paste((as.character(counts[,1]))), 
        main=paste0("Cluster ",i, ",", j, " #PoS ",length(res.som$Clusters[[i,j]]))) 
 }
}  

Rplot01

1 个答案:

答案 0 :(得分:1)

你的问题不是绘图,而是在绘图之前操纵你的数据。我无法弄清楚你想要做什么,但这是我的尝试。它看起来与你的不同,但我无法弄清楚你想要绘制的内容。通常,要在网格上绘图,您可以将变量收集到整齐的格式(每行1次观察),然后使用刻面。

library(tidyverse)

centers.df <- data.frame(clust1 = sample(c(1,2), 50, replace=T),
                         clust2 = sample(c(1,2), 50, replace =T),
                         brand = sample(letters[1:4], 50, replace = T),
                         cpal = sample(LETTERS[1:4], 50, replace = T),
                         center = rnorm(100))

centers.df <- centers.df %>% 
  gather(clust, num, clust1:clust2) %>% 
  group_by(clust, num, cpal) %>% 
  summarise(center_count = sum(center))


ggplot(centers.df, aes(x = cpal, y = center_count, fill = cpal)) + 
  geom_col() + 
  facet_grid(clust~num)

Plot