下面显示的是使用 Plotly 创建的树形图。您可以在下面找到相应的代码和图表。
我很欣赏这张图的风格,并打算使用 ggplot2 复制它。下面,您将看到使用 ggplot2 生成的树形图。
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 中 Plotly 中分隔矩形的白线或空白空间时遇到了困难。 下面你可以看到我的 ggplot2 树形图。
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",
#place = "left",
size = 8,
fontface = "bold") +
scale_fill_brewer(palette = "Set1")+
labs(title = "Treemap with Percentage Share by Group")+
theme(legend.position = "none")
有人可以帮助我实现矩形之间的这种效果(白线或空白)吗?
您可以使用
color=
中的 size=
和 geom_treemap
添加轮廓。我还在您的标签中添加了一些换行符和更多填充:
library(treemapify)
library(ggplot2)
ggplot(
df,
aes(
area = percentage, fill = group,
label = paste0(subgroup, ":\n", value, "\n", round(percentage, 2), "%")
)
) +
geom_treemap(color = "white", size = 4) +
geom_treemap_text(
colour = "white",
size = 8,
fontface = "bold",
padding.x = unit(2, "mm"),
padding.y = unit(2, "mm")
) +
scale_fill_brewer(palette = "Set1") +
labs(title = "Treemap with Percentage Share by Group") +
theme(legend.position = "none")