如何修改Treemap深色矩形标签颜色及匹配R默认字体
解决方案
1. 将最深色矩形的标签改为白色
你的填充色是按perc值排序的红色系调色板,最深色对应perc最大的类别(即"Motor Vehicle Insurance")。可以通过在geom_treemap_text中添加颜色映射,为该类别单独设置白色标签:
- 在
geom_treemap_text的aes里增加color参数,用ifelse判断是否为最大perc的类别,直接指定对应颜色 - 配合
scale_color_identity()让ggplot直接使用我们定义的颜色值
2. 修改标签字体为R默认字体
R的默认字体是系统对应的无衬线字体族(Windows为Arial,macOS为Helvetica,Linux为DejaVu Sans),在ggplot2中直接给geom_treemap_text添加family="sans"参数,即可匹配这个默认字体。
修改后的完整代码
# 创建数据框 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))(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, "%"), # 为最大perc的类别设置白色标签 color = ifelse(perc == max(df$perc), "white", "black") ), place = "centre", size = 12, # 使用R默认无衬线字体 family = "sans" ) + scale_fill_manual(values = pal_fill) + scale_color_identity() + labs(title = "Categories Contributing Most to Inflation in 2023") + guides(fill = "none")
补充说明
如果需要给多个深色矩形(比如前N个高perc类别)设置白色标签,可以把ifelse条件改成perc >= quantile(df$perc, 0.9)这类分位数判断,灵活适配需求。
内容的提问来源于stack exchange,提问作者Data and AI Nerd
相关产品推荐
相关产品推荐

