我想在R中生成热图,其中单元格区域和颜色由两列控制。例如,在下面的数据中,我希望每个单元格的面积与“计数”列成比例,颜色由“度量”列控制,并在每个单元格上放置“等级”标签。我怎么能在R?中做到这一点?
Event measure rank Count
A 20 1 2000
B 15 2 1870
C 10 3 1540
D 5 4 1200
答案 0 :(得分:3)
您正在寻找的地图类型称为树形图。 我已编辑了答案,根据您的评论在地块下方添加了一张表格。
library("treemap")
library("grid")
library("gridExtra")
mydat <- structure(list(Event = structure(1:4, .Label = c("A", "B", "C",
"D"), class = "factor"), measure = c(20L, 15L, 10L, 5L), rank = 1:4,
Count = c(2000L, 1870L, 1540L, 1200L)), .Names = c("Event",
"measure", "rank", "Count"), class = "data.frame", row.names = c(NA, -4L))
# Setup the parent layout viewport
layout_vp <- viewport(layout = grid.layout(nrow = 2, ncol = 1,
widths = unit(c(1, 1), "npc"),
heights = unit(c(0.6, 0.4), "npc")), name = "lay_vp")
# Specify the location of the top and bottom viewports for the tree plot and table
tree_vp <- viewport(layout.pos.col = NULL, layout.pos.row = 1, name = "vp_top")
table_vp <- viewport(layout.pos.col = NULL, layout.pos.row = 2, name = "vp_bottom",
height = unit(0.1, "npc"))
# Create grob for table
table_grob <- tableGrob(mydat, rows = NULL, vp = table_vp)
# Combining the treemap and table
grid.newpage()
pushViewport(layout_vp)
pushViewport(tree_vp)
treemap(mydat, index = "rank", vSize = "Count", vColor = "measure", type = "value",
position.legend = "none", vp = tree_vp)
popViewport()
pushViewport(table_vp)
grid.draw(table_grob)
popViewport()
给予