简体   繁体   中英

Functional programming with Tidyr's "gather" and Ggplot2 for More Rapid Visual Data Exploration

The example code below ( using the happy dataset from productplots or ggmosaic ) lets me quickly visualize various categorical variables (sex, marital, health, and degree)broken down by happiness (happy). To accomplish this, I have to separate out the variable I want to condition on from the "gather" function, in this case, "happy". But what if I want to change this variable? Or create another combination? I'll have to continually reproduce the code below and change the variables. Is there a faster way to accomplish this with a function? Can the purrr package help in some way?

Df1<-happy%>%
select(sex, happy, marital, health, degree)%>%
gather(key, value, -happy)%>%
count(happy, key, value)%>%
na.omit()%>%
mutate(perc=round(n/sum(n),2))

P<-ggplot(H5)+geom_col(aes(x=value,y=perc,fill=happy))+facet_wrap     
(~key,scales="free")+geom_text(aes
(x=value,y=perc,label=perc,group=happy),position=position_stack(vjust=.05))

I would like a solution(s) based on the Tidyverse as much as possible.

As long as you are looking at the same set of columns, you can wrap this in a function by converting to the standard evaluation versions of each of the functions you use. Here is your same code, just tweaked to run in a function:

plotLook <- function(thisCol = "happy"){
  happy %>%
    select(sex, happy, marital, health, degree) %>%
    gather_("key", "value"
            , names(.)[names(.) != thisCol]
            )%>%
    count_(c(thisCol, "key", "value")) %>%
    na.omit() %>%
    mutate(perc=round(n/sum(n),2)) %>%
    ggplot() + 
    geom_col(aes_string(x="value",y="perc",fill=thisCol)) +
    facet_wrap(~key,scales="free") +
    geom_text(aes_string(x="value",y="perc"
                         ,label="perc",group= thisCol)
              ,position=position_stack(vjust=.05))
}

Now this:

plotLook("sex")

generates:

在此处输入图片说明

Even better, you can then use lapply to generate all of the plots in one go:

lapply(c("sex", "happy", "marital", "health", "degree"), plotLook)

and either save the output to use/modify, or just let them print to the screen.

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