Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

r - How to add bounding box to a specific area in ggplot2 heatmap?

I use an example from here. My question is how can I add a specific bounding box to this heatmap, such as add a red line box to the top left four tiles?

require(ggplot2)
require(reshape)
require(scales)

mydf <- data.frame(industry = c('all industries','steel','cars'), 
    'all regions' = c(250,150,100), americas = c(150,90,60), 
     europe = c(150,60,40), check.names = FALSE)
mydf

mymelt <- melt(mydf, id.var = c('industry'))
mymelt

ggplot(mymelt, aes(x = industry, y = variable, fill = value)) +
    geom_tile() + geom_text(aes(fill = mymelt$value, label = mymelt$value))

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A quick and dirty (some hard-coding) possibility is to use geom_rect, where the positions are given by the numerical values of the levels of x and y variables to be bound with a box, plus/minus an offset.

ggplot(mymelt, aes(x = industry, y = variable, fill = value, label = value)) +
  geom_tile() +
  geom_text() +
  geom_rect(aes(xmin = 1 - 0.5, xmax = 2 + 0.5, ymin = 2 - 0.5, ymax = 3 + 0.5),
               fill = "transparent", color = "red", size = 1.5)

enter image description here

A less hard-coded version:

# convert x and y variables to factors
ind <- as.factor(mymelt$industry)
vars <- as.factor(mymelt$variable)

# numeric version of the levels to be bound by a box
xmin <- unique(as.numeric(ind[ind == "all industries"]))
xmax <- unique(as.numeric(ind[ind == "cars"]))

ymin <- unique(as.numeric(vars[vars == "americas"]))
ymax <- unique(as.numeric(vars[vars == "europe"]))

# set offset
offset <- 0.5

ggplot(mymelt, aes(x = industry, y = variable, fill = value, label = value)) +
  geom_tile() +
  geom_text() +
  geom_rect(aes(xmin = xmin - offset,
                xmax = xmax + offset,
                ymin = ymin - offset,
                ymax = ymax + offset),
            fill = "transparent", color = "red", size = 1.5)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...