Search code examples
rggplot2aesthetics

Geom aesthetic only for some level or category


I am trying to control geom aesthetic for some category or level, example

  library(ggplot2)
  library(ggrepel)
  library(treemapify)

    set.seed(123)
    Cases = round(rnorm(16, 500, 22))
    Country = LETTERS[seq( from = 1, to = 16 )]
    df = data.frame(Cases,Country)

    df=rbind(df, data.frame(Country='Total', Cases = round(sum(df$Cases))))

   ggplot(df, aes(area =Cases , fill = Country, label = Cases)) +
        geom_treemap() +
        geom_treemap_text(fontface = "bold.italic", colour = "white", place = "centre", grow = T,  min.size = 1)  

This produce this plot:

plot1

My goal is get a graph like that, where Total size is similar to others countries to make this example I delete Total row, only for the purpose to display the size of the differents numbers in each country.

    df=df[!grepl('Total',df$Country),]

    ggplot(df, aes(area =Cases , fill = Country, label = Cases)) +
        geom_treemap() +
        geom_treemap_text(fontface = "bold.italic", colour = "white", place = "centre", grow = T,  min.size = 1)  

plot2

My goal is get the total size like the size of others Countries. To do this i tried to control grow = F with a filter, this is my example:

ggplot(df, aes(area =Cases , fill = Country, label = Cases)) +
geom_treemap() +
{if(df$Country=="Total") geom_treemap_text(fontface = "bold.italic", colour = "white", place = "centre", grow = F,  min.size = 1)} +
{if(df$Country!="Total") geom_treemap_text(fontface = "bold.italic", colour = "white", place = "centre", grow = T,  min.size = 1)}                               

Solution

  • To keep the size same you can give area a static value instead of using cases.

    library(ggplot2)
    library(ggrepel)
    library(treemapify)
    
    
    ggplot(df, aes(area = 10 , fill = Country, label = Cases)) +
      geom_treemap() +
      geom_treemap_text(fontface = "bold.italic", colour = "white", 
                        place = "centre", grow = T,  min.size = 1)  
    

    enter image description here