Home > Back-end >  refer to table in ggplot function
refer to table in ggplot function

Time:06-28

I have a plotting pipeline as follows

df %>% 
    count(sub_category, name="count") %>%
    arrange(desc(count)) %>%
    slice_head(n=10) %>%
    ggplot(aes(x=reorder(sub_category, count), y=count))  
        geom_bar(stat='identity', fill='steelblue')  
        geom_text(aes(label=count), position=position_stack(vjust=0.5))  
        labs(title="Top 10 Sub-Categories", x="Product Sub-Category", caption=paste0('total items=', sum(count)))
    

As you can in above code, only the top 10 rows of df (grouped by sub-category) are supplied to ggplot() and in the labs() function I am trying to add a caption with total number of items (rows) included only in the top 10 rows. Is there a way to refer to table used by ggplot, something like in dplyr we can do .$count or .data[['count']]?

I know I can store the intermediate table and then pass it to ggplot2, but I am just curious if there is a way to do the above without storing the intermediate results.

CodePudding user response:

Yes this is possible. Try this one

mtcars %>% 
  {ggplot(data=., aes(disp, hp))   
   geom_point()   
   labs(title="Top 10 Sub-Categories", 
        x="Product Sub-Category", 
        caption=paste0('total items=', sum(.$cyl)))}
  • Related