遍历数据框以在R中创建图

时间:2019-12-12 15:45:59

标签: r loops ggplot2

我知道这里有一个非常类似的问题:Multiple plots using loops in R,但是我一直试图模仿它而没有成功,尽管我认为我已经很接近了。为简单起见,我的数据帧district.charter.comp如下:

 city.state     count     school.type     Status
Stockton, CA     1417      charter     Beat the Odds
Stockton, CA     7242      charter    Not Beat the Odds
Stockton, CA     269       district    Beat the Odds
Stockton, CA    49737      district   Not Beat the Odds
 Newark, NJ     12528      charter     Beat the Odds
 Newark, NJ      3687      charter    Not Beat the Odds
 Newark, NJ      7129      district    Beat the Odds
 Newark, NJ     27257      district   Not Beat the Odds

对于每个城市州,我想创建一个独特的镶嵌图或mekko图。我当前的代码如下:

district.charter.comp$city.state <- as.factor(district.charter.comp$city.state)

for(i in levels(district.charter.comp$city.state)) {
  mekko.plot <- district.charter.comp %>% filter(city.state == i) %>% 
  ggplot() +
  geom_mosaic(aes(weight = count, x = product(school.type), fill = Status)) +
  theme(axis.ticks = element_blank(),
        axis.title = element_blank(),
        axis.text = element_blank(),
        legend.position = "none") +
  ggtitle(i) +
  theme(plot.title = element_text(hjust = 0.5))
  mekko.plot
}
plot.data

但是,当我查看图时,我仅得到Stockton, CA,并且循环似乎并没有迭代到下一个因子水平,即Newark, NJenter image description here

循环应输出两个图。一个用于Stockton, CA,另一个用于Newark, NJ

1 个答案:

答案 0 :(得分:2)

考虑bytapply的面向对象包装器),这等效于遍历因子的所有级别。另外,像Apply系列函数一样,by返回一个对象或对象集合(在此为列表),而无需进行簿记初始化和分配给空列表。

mekko.plots <- by(district.charter.comp, district.charter.comp$city.state, function(sub) {
  ggplot(sub) +
    geom_mosaic(aes(weight = count, x = product(school.type), fill = Status)) +
    theme(axis.ticks = element_blank(),
          axis.title = element_blank(),
          axis.text = element_blank(),
          legend.position = "none") +
    ggtitle(sub$city.state[[1]]) +
    theme(plot.title = element_text(hjust = 0.5))
})

mekko.plots