简体   繁体   中英

heatmap in R with cell area proportional to an observation

I want to produce heatmap in R where the cell area and color are governed by two columns. For example, in the data below, I want the area of every cell to be proportional to the "count" column and the color to be controlled by the "measure" column and put the "rank" label on each cell. How can I do this in R?

   Event    measure rank    Count
   A         20     1      2000
   B         15     2      1870
   C         10     3      1540
   D         5      4      1200

The type of plot you're looking for is called a treemap. I've edited the answer to include a table below the plot based on your comment.

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()

Giving

带有表的树图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM