简体   繁体   中英

Loop Through Dataframe to Create Plots in R

I know there is a very similar question to this found here: Multiple plots using loops in R but I have been trying to emulate it without success, though I think I am quite close. For simplicity, my dataframe, district.charter.comp , is as follows:

 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

For each city state, I want to create a unique mosaic or mekko plot. My current code is as follows:

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

However, when I view the plot, I get only Stockton, CA and the loop doesn't appear to be iterating through to the next factor level, namely Newark, NJ . 在此处输入图片说明

The loop should output two plots. One for Stockton, CA and another for Newark, NJ .

Consider by (object-oriented wrapper to tapply ) which is equivalent to looping through all levels of a factor. Plus, like the apply family functions, by returns an object or collection of objects (here being list) without the bookkeeping of initializing and assigning to an empty list.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM