如何在ggplot2中复刻Plotly树形图的白色分隔线效果?
如何在ggplot2树形图中添加矩形间的白色分隔线
我喜欢Plotly制作的树形图样式(矩形块之间带有白色空白分隔),想用ggplot2配合treemapify包复刻该效果,但当前实现的树形图没有白色分隔线,恳请协助解决。
Plotly树形图示例
Plotly生成的树形图中,每个品牌对应的矩形区块间有明显的白色空白分隔,清晰区分不同条目:
library(ggplot2) library(plotly) library(dplyr) df1<-structure(list(manuf = c("AMC", "Cadillac", "Camaro", "Chrysler", "Datsun", "Dodge", "Duster", "Ferrari", "Fiat", "Ford", "Honda", "Hornet", "Lincoln", "Lotus", "Maserati", "Mazda", "Merc", "Pontiac", "Porsche", "Toyota", "Valiant", "Volvo"), count = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 7L, 1L, 1L, 2L, 1L, 1L)), row.names = c(NA, -22L), class = c("tbl_df", "tbl", "data.frame")) df1$test<-"CARS" treemap<-plot_ly(data = df1, type= "treemap", values= ~count, labels= ~manuf, parents= ~test, domain= list(column=0), name = " ", textinfo="label+value+percent parent") %>% layout(title="", annotations = list(x = 0, y = -0.1, title = "", text = " ", showarrow = F, xref='paper', yref='paper')) treemap
我的ggplot2树形图实现
目前用ggplot2+treemapify制作的树形图没有白色分隔线,区块紧密相连:
library(treemapify) library(ggplot2) group <- paste("Group", 1:9) subgroup <- c("A", "C", "B", "A", "A", "C", "C", "B", "B") value <- c(7, 25, 50, 5, 16, 18, 30, 12, 41) df <- data.frame(group, subgroup, value) # Calculate percentage share for each group df$percentage <- df$value / sum(df$value) * 100 test_treemap<-ggplot(df, aes(area = percentage, fill = group, label = paste(subgroup, ": ", value, " (", round(percentage, 2), "%)"))) + geom_treemap() + geom_treemap_text(colour = "white", hjust = "left", size = 8, fontface = "bold") + scale_fill_brewer(palette = "Set1")+ labs(title = "Treemap with Percentage Share by Group")+ theme(legend.position = "none")
解决方案:添加白色分隔线
只需在geom_treemap()中加入color = "white"和size参数,即可为每个矩形区块添加白色边框,模拟出类似Plotly的分隔效果。size值可根据需求调整,控制分隔线的宽度:
library(treemapify) library(ggplot2) group <- paste("Group", 1:9) subgroup <- c("A", "C", "B", "A", "A", "C", "C", "B", "B") value <- c(7, 25, 50, 5, 16, 18, 30, 12, 41) df <- data.frame(group, subgroup, value) # Calculate percentage share for each group df$percentage <- df$value / sum(df$value) * 100 test_treemap<-ggplot(df, aes(area = percentage, fill = group, label = paste(subgroup, ": ", value, " (", round(percentage, 2), "%)"))) + # 添加白色边框作为分隔线 geom_treemap(color = "white", size = 2) + geom_treemap_text(colour = "white", hjust = "left", size = 8, fontface = "bold") + scale_fill_brewer(palette = "Set1")+ labs(title = "Treemap with Percentage Share by Group")+ theme(legend.position = "none")
如果想要更接近Plotly的"空白分隔"而非实线边框,可以尝试调大size参数,或者结合theme(panel.background = element_rect(fill = "white"))强化视觉效果。
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

