gpt4 book ai didi

r - 将树状图转换为 ggplot

转载 作者:行者123 更新时间:2023-12-05 02:19:26 26 4
gpt4 key购买 nike

好消息:我可以使用 treemap 包创建漂亮的树状图。

数据:

forTm <- structure(list(
UnitGroup = c("1N", "BHU", "CSU", "ED", "Med/Surg", "Med/Surg", "Telemetry",
"Telemetry", "Telemetry", "Telemetry", "Telemetry"),
Unit = c("A", "B", "C", "ED", "D", "E", "F", "G", "H", "I", "J"),
Count = c(1L, 1L, 1L, 1L, 15L, 10L, 5L, 2L, 3L, 8L, 4L)),
class = c("data.frame"),
row.names = c(NA, -11L),
.Names = c("UnitGroup", "Unit", "Count"))

树状图:

library(treemap)
tm <- treemap(forTm,
index = c("UnitGroup", "Unit"),
vSize = "Count",
vColor = "Count",
type = "dens",
palette = "YlGnBu",
title = "# Patients Sample Title",
aspRatio = (1.5),
fontsize.labels = c(16, 12),
fontsize.title = 16,
bg.labels = "white",
border.lwds = c(5,0))

问题:class(tm) 是一个列表,我需要在包含多个 ggplot 的页面上绘制树状图。我预计需要为最终用户添加/重新排列图,所以我想要一个相对灵活的解决方案。

目标:将树状图插入以下仪表板:

#just stand-ins for the plots
samplePlot <- grid.rect(gp = gpar(fill = "grey"))
treemapHere <- grid.rect(gp = gpar(fill = "blue"))

grid.arrange(samplePlot, # plot 1
treemapHere, # plot 2
samplePlot, # plot 3
layout_matrix = rbind(c(3, 2), c(1, 1)),
top = textGrob("Sample Title",
gp = gpar(margin = margin(10, 0, 10, 0))),
heights = c(5, 5))

但解决方案需要足够灵活,以便我可以轻松添加/重新排列绘图,例如如下:

grid.arrange(samplePlot, # plot 1
samplePlot, # plot 2
samplePlot, # plot 3
samplePlot, # plot 4
treemapHere, # plot5
layout_matrix = rbind(c(1, 2, 3),
c(4, 5, 5)),
top = textGrob("Sample Title",
gp = gpar(margin = margin(10, 0, 10, 0))),
heights = c(5, 5))

理想情况下,我会找到一种方法将树状图重新创建为 ggplot,因为我非常熟悉 ggplot 的语法,所以我可以轻松地标准化工作表的样式。但如果没有办法做到这一点,我会接受任何解决方案(将树状图保存为 grob?),让我可以轻松地在我的 ggplots 页面中重新排列此图。

到目前为止我尝试过的:老实说,不多。谷歌一直不是我的 friend 。我发现的唯一建议是使用 treemapify,我不能为这个特定项目做。

最佳答案

如果您使用 ggplot 逐步重建树状图会怎样?例如

library(tidyverse)
treemapHere <- ggplot(tm$tm,
aes(xmin=x0+w, xmax=x0, ymin=y0+h, ymax=y0, fill=ifelse(level==1, NA, color), fill = vSize)) +
scale_fill_identity() +
geom_rect(aes( size=I((2:1)[level])), color="#303030") +
coord_fixed(0.75) +
guides(size="none") +
cowplot::theme_nothing() +
geom_text(aes(x0+w/2, y0+h/2, label=Unit, size=I(scales::rescale(vSize, c(2.5, 3))))) +
geom_label(aes(x, y, label=UnitGroup, size=I(scales::rescale(vSize, c(2.5, 7)))), tm$tm %>% group_by(UnitGroup) %>% summarise(x=mean(x0+w/2), y=mean(y0+h/2), vSize=mean(vSize)), inherit.aes=F, fill="white", fontface = "bold")

library(grid)
library(gridExtra)
samplePlot <- grid.rect(gp = gpar(fill = "grey"))
grid.arrange(samplePlot, # plot 1
samplePlot, # plot 2
samplePlot, # plot 3
samplePlot, # plot 4
treemapHere, # plot5
layout_matrix = rbind(c(1, 2, 3),
c(4, 5, 5)),
top = textGrob("Sample Title",
gp = gpar(margin = margin(10, 0, 10, 0))),
heights = c(5, 5))

enter image description here

关于r - 将树状图转换为 ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42866566/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com