如何为R语言Treemap添加交互式标签及自定义样式?
问题
我希望为使用ggplot2和treemapify绘制的树形图添加可显示类别与百分比的交互式标签,请问是否有实现方法?另外,我想将颜色设置为单一色系,让数值最高的区域呈现最深的色调,能否实现?同时我还需要移除图例。现有代码如下:
# Importing required library library(ggplot2) library(treemapify) # Creating Dataframe df<- data.frame(Fruits=c("Owners' Equivalent Rent of Residences", "Rent of Primary Residence", "New Vehicles", "Used Cars and Trucks", "Cereals And bakery Products", "Motor Vehicle Maintenance and Repair", "Airline Fares", "Apparel", "Medical Care Commodities", "Alcoholic Beverages", "Hospital Services", "Tobacco and Smoking", "Physicians Services", "Gasoline All Types", "Electricity", "Utility (Piped) Gas Services", "Nonalcoholic Beverages and Beverage Materials", "Food Away From Home", "Meats Poultry Fish and", "Fruits and Vegetables", "Dairy and Related Products", "Cereals And Bakery Products", "Other Foods at Home"), perc=c(6.7, 6.9, 1.3, -3.8, 19.2, 8.5, -12.1, 1.1, 5, 2.9, 6.3, 7.7, 0.7, -8.9, 3.4, -10.4, -2.9, 5.3, 0.1, 0.4, -1.4, 3.4, 3.3)) # Plotting TreeMap Graph ggplot2::ggplot(df,aes(area=perc,fill=Fruits,label=Fruits))+ treemapify::geom_treemap(layout="squarified")+ geom_treemap_text(place = "centre",size = 12) labs(title="Customized Tree Plot using ggplot and treemapify in R")
解决方案
以下是同时满足三个需求的修改方案,附完整代码和说明:
完整修改代码
# 加载所需工具包 library(ggplot2) library(treemapify) library(plotly) # 创建数据框(保留原数据) df <- data.frame( Fruits = c("Owners' Equivalent Rent of Residences", "Rent of Primary Residence", "New Vehicles", "Used Cars and Trucks", "Cereals And bakery Products", "Motor Vehicle Maintenance and Repair", "Airline Fares", "Apparel", "Medical Care Commodities", "Alcoholic Beverages", "Hospital Services", "Tobacco and Smoking", "Physicians Services", "Gasoline All Types", "Electricity", "Utility (Piped) Gas Services", "Nonalcoholic Beverages and Beverage Materials", "Food Away From Home", "Meats Poultry Fish and", "Fruits and Vegetables", "Dairy and Related Products", "Cereals And Bakery Products", "Other Foods at Home"), perc = c(6.7, 6.9, 1.3, -3.8, 19.2, 8.5, -12.1, 1.1, 5, 2.9, 6.3, 7.7, 0.7, -8.9, 3.4, -10.4, -2.9, 5.3, 0.1, 0.4, -1.4, 3.4, 3.3) ) # 绘制树形图并转为交互式 p <- ggplot(df, aes(area = abs(perc), fill = perc, label = Fruits)) + geom_treemap(layout = "squarified") + geom_treemap_text(place = "centre", size = 10, color = "white") + # 设置单一色系:数值越高颜色越深 scale_fill_gradient(low = "#cce5ff", high = "#00264d") + # 移除图例 theme(legend.position = "none") + labs(title = "自定义树形图(含交互标签)") # 转换为交互式图表,鼠标悬停显示类别和百分比 ggplotly(p, tooltip = c("label", "perc"))
关键改动说明
交互式标签实现
- 引入
plotly包,将静态ggplot对象转为交互式图表,鼠标悬停时自动显示类别(Fruits)和百分比(perc) - 用
ggplotly()函数转换,通过tooltip参数指定要显示的内容
- 引入
单一色系按数值深浅着色
- 将
fill映射从Fruits改为perc,让颜色随百分比数值变化 - 用
scale_fill_gradient()设置单一色系,low对应数值最低的浅色调,high对应数值最高的深色调,可自行替换颜色代码(比如米色到棕色:low="#f5f5dc", high="#8b4513") - 因为树形图的
area不能为负数,所以用abs(perc)确保区域大小为正,颜色仍映射原始正负数值
- 将
移除图例
- 直接添加
theme(legend.position = "none")即可隐藏图例
- 直接添加
内容的提问来源于stack exchange,提问作者Data and AI Nerd
相关产品推荐
相关产品推荐

