How to change colors and font of treemap labels

I would like to change the color of the labels on the darkest rectangles of my treemap to white to increase readability. Is there a way to do this? I also would like to change the font of my labels. Ideally I would like the font to match the base R default font (I’m not sure what that font is called?). Is there a way to change the label fonts?

# Creating Dataframe 
 subgroup <-c()
 df<- data.frame(Fruits=c("Owners' Equivalent Rent of Residences", 
                     "Rent of Primary Residence",
                     "New Vehicles", 
                    
    "Motor Vehicle Insurance",
                     "Motor Vehicle Maintenance and Repair",
                    
                     "Apparel", 
                     "Medical Care Commodities",
                     "Alcoholic Beverages", 
                     "Hospital Services",
                     "Tobacco and Smoking",
                     "Physicians Services",
                     "Gasoline All Types",
                     "Electricity", 
                    
                    
                     "Food Away From Home", 
                     "Meats Poultry Fish and Eggs", 
                     "Fruits and Vegetables", 
                     "Dairy and Related Products",
                     "Cereals And Bakery Products", 
                     "Other Foods at Home"), 
            perc=c(6.7, 6.9, 1.3, 19.2, 8.5, 1.1, 5, 2.9, 
                   6.3, 7.7, 0.7, -8.9, 3.4, 5.3, 0.1, 0.4, 
                   -1.4, 3.4, 3.3)) 
 library(ggplot2)
 library(treemapify)

 pal_fill <- colorRampPalette(scales::brewer_pal(palette = "Reds")(9))
 pal_fill <- pal_fill(length(unique(df$Fruits)))
 names(pal_fill) <- levels(reorder(df$Fruits, df$perc))

 ggplot(df, aes(area = perc, fill = Fruits, label = Fruits)) +
  geom_treemap(layout = "squarified") +
  geom_treemap_text(
   aes(label = paste0(Fruits, "\n", perc, "%")),
 place = "centre", size = 12
  ) +
 scale_fill_manual(values = pal_fill) +
 labs(title = "Categories Contributing Most to Inflation in 2023") +
 guides(fill = "none")

Leave a Comment