r - multiple line and facet_grid in Bar plot -


i have dataframe 53 states , sex variable. e.g. below df having 26 states.

set.seed(25) test <- data.frame(   state = sample(letters[1:26], 10000, replace = true),    sex = sample(c("m","f"), 10000, replace = true) ) 

now want see state has more female member, created bar plot in grid each state , each grid has 2 bars (m,f).

test.pct = test %>% group_by(state, sex) %>%   summarise(count=n()) %>%   mutate(pct=count/sum(count))   ggplot(test.pct, aes(x=sex, y=pct, fill=sex)) +   geom_bar(stat="identity") +   facet_grid(. ~ state)  

the problem these 26 grid appearing in single line - visibility issue. want construct plot in multiple frame, e.g 3x9 instead of 1x26.

also state should ordered based of female percentage.

thanks help.

problem #1: use facet_wrap. problem #2: reorder state levels beforehand.

it this:

ggplot(transform(test.pct, state=factor(state,                                          levels=with(subset(test.pct, sex=="f"),                                                      state[order(pct)]))),         aes(x=sex, y=pct, fill=sex)) +   geom_bar(stat="identity") +   facet_wrap(~ state, nrow = 3)  

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -